//global vars
var rate_weekday_am = [];
 	rate_weekday_pm = [],
    rate_weekday_ev = [],
	rate_weekend_am = [],
	rate_weekend_pm = [],
	rate_weekend_ev = [];

var rate_mon_am = [],
	rate_mon_pm = [],
	rate_mon_ev = [],
	rate_tue_am = [],
	rate_tue_pm = [],
	rate_tue_ev = [],
	rate_wed_am = [],
	rate_wed_pm = [],
	rate_wed_ev = [],
	rate_thu_am = [],
	rate_thu_pm = [],
	rate_thu_ev = [],
	rate_fri_am = [],
	rate_fri_pm = [],
	rate_fri_ev = [],
	rate_sat_am = [],
	rate_sat_pm = [],
	rate_sat_ev = [],
	rate_sun_am = [],
	rate_sun_pm = [],
	rate_sun_ev = [];	

var rate_opt_15min = 5; //extention time

//catering options
var rate_opt_c_cnt0 = 20, rate_opt_c_cnt1 = 30; //coffee and tea
var rate_opt_c_tc0 = 4, rate_opt_c_tc1 = 4.5, rate_opt_c_tc2 = 4.8, rate_opt_c_tc3 = 5;//tea reception
var rate_opt_c_ldb0 = 9, rate_opt_c_ldb1 = 10, rate_opt_c_ldb2 = 12;//lunch/dinner box

//visual options
var rate_opt_pws = 20; //projector with screen
var rate_opt_so = 10; //screen only
var rate_opt_fcwp = 10; //flipchart with paper
var rate_opt_fcm = 10; //flipchart marker
var rate_opt_wb = 10; //white board wiht marker
//audio options
var rate_opt_mic_co = 20; //mic clip-on with audio system
var rate_opt_mic_hh = 15; //mic hand-held with audio system
var rate_opt_aso = 10; //audio system only
var rate_opt_ms = 5;	//mic stand	
//connection options
var rate_opt_wic = 10; //wireless internet connection
var rate_opt_wnt = 10; //wireless NETS terminal
//layout options
var rate_opt_tbl = 5; //table
var rate_opt_layout = 10; //layout
//public holiday
var rate_opt_ph = 50;

var rate_surcharge = 0;

//standard start end time
var hour_start_am = 9;
var hour_start_pm = 14;
var hour_start_ev = 19;
var hour_end_am = 12;
var hour_end_pm = 17;
var hour_end_ev = 22;

var minute_start_am = 0;
var minute_start_pm = 0;
var minute_start_ev = 0;
var minute_end_am = 0;
var minute_end_pm = 0;
var minute_end_ev = 0;

//(08:30,08:15,08:00,07:45,07:30)(13:00,13:15,13:30)(18:30)
//(12:45,13:00)(17:30,17:45,18:00,18:15,18:30)(22:30,22:45,23:00,23:15,23:30)
var	early_step_am = 5;
var extend_step_am = 2;
var	early_step_pm = 3;
var extend_step_pm = 5;
var	early_step_ev = 1;
var extend_step_ev = 5;
var	early_step_fc1 = early_step_am;
var extend_step_fc1 = extend_step_pm;
var	early_step_fc2 = early_step_pm;
var extend_step_fc2 = extend_step_ev;
var	early_step_cd = early_step_am;
var extend_step_cd = extend_step_ev;

var title_indicator = 'Please enter your event title here (max 60 characters)';

var tab_add_options = null;

var tab_date_enabled = false;
var tab_option_enabled = false;
var tab_summary_enabled = false;
var tab_booking_enabled = false;

var btn_sd_add_date = null;
var btn_sd_add_options = null;
var btn_sd_clear_dates = null;
var btn_bn_restart_booking = null;
var btn_bc_new_booking = null;
var btn_ppbtn_div = null;

var box_datetimebox_container = null;
var box_option_timing_container = null;
var	box_booking_summary_container = null;
var	box_book_now_container = null;
var	box_complete_container = null;	
var box_client_info_container = null;

var nodtb = 0; //number of datetimboxes injected
var nodtb_max = 10;
var global_box_id = 0;

//booking_status "admin[client]_in_progress"->"admin[client]_pending"->"admin[client]_confirmed"
var booking_status = "";
var user_group = null;

var noae = 4;//number of additional entries in the booking entry array
//1 sum amt //2 booking number //3 additional message
var norts = 3; //number of return status elements

var nor = 8; //number of rooms
var current_room = 'action_room';

var global_countdown_stop = false;//for killing countdown event
var global_countdown_timers = 0;

var pickershowing = false;

window.addEvent('domready', function(){

//assign global vars
tab_add_options = $('tab_add_options');

btn_sd_add_date = $('btn_sd_add_date');
btn_sd_add_options = $('btn_sd_add_options');
btn_sd_clear_dates = $('btn_sd_clear_dates');
btn_bn_restart_booking = $('btn_bn_restart_booking');
btn_bc_new_booking = $('btn_bc_new_booking');
btn_ppbtn_div = $('ppbtn');

box_datetimebox_container = $('box_datetimebox_container');
box_option_timing_container = $('box_option_timing_container');
box_booking_summary_container = $('csmbol-booking-summary-box');
box_book_now_container = $('csmbol-booking-box');
box_complete_container = $('csmbol-booking-completed-box');	
//box_client_info_container = $('box_client_info_container');

var csmbol_tabs = $$('.csmbol-tabs LI.csmbol-tab'),
    csmbol_content = $$('.csmbol-tabcontent');

csmbol_tabs.each(function(tab, index){
		tab.addEvent('click', function(event){
			event.stop();
			csmbol_tabs.removeClass('selected');
			csmbol_content.removeClass('selected');
			csmbol_tabs[index].addClass('selected');
			csmbol_content[index].addClass('selected');
		});
    });
});

function disableOption(itemId){
	var option_element = $$(itemId);
	option_element.disabled = true;
}

function enableOption(itemId){
	var option_element = $$(itemId);
	option_element.disabled = false;
}

window.addEvent('domready', function(){
	disableFunctions();
	//checking booking status
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=iniBooking&format=raw',
		onRequest: function(){
		},
		onComplete: function(response){
			var container_box_id = 'box_datetimebox_container';
			if(response.rts =='error'){
				disableFunctions();				
				$(container_box_id).set('html', response.rtmsg+response.rtmsg_embeded_code)
				 return;
			}				
			
			booking_status = response.booking_status;
			user_group = response.user_group;	
			if(String(booking_status)!='payment_done'){ 
				booking_status = 'guest_visit';
				if(isEventOrganizer(user_group)) booking_status = 'client_in_progress';
				if(isStaff(user_group)) booking_status = 'admin_in_progress';
			}			
			switch (String(booking_status)){
			case 'admin_in_progress':
			case 'client_in_progress':
				startNewBookingSession(response);
				break;
			case 'guest_visit':	
				showRegistration();	 	
				break;	
			case 'payment_done':
				completeClientBookingNow();
				break;
			case 'cancel':
				window.alert('cancel');
				break;
			case 'test':
		new Request.JSON({
				url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=test&format=raw',
				onRequest: function(){
				},
				onComplete: function(response){
					window.alert('test');
				}
			}).send();					
			default:
				break;			
			};			
		}
	}).send(/*'current_room='+current_room*/);			
				
	var btn_addDate = $('btn_sd_add_date');
	//registering 'click' event for the 'Add Date' button
	btn_addDate.addEvent('click', function(event){
		event.stop();	
		if(nodtb < nodtb_max){
			var box_number = global_box_id+1;//nodtb+1;
			var datetimebox = new Element( 'div.csmbol-datetimebox', {'id': 'csmbol-datetimebox-'+box_number});
			box_datetimebox_container.grab(datetimebox);		
			var date_div = new Element('div.csmbol-date',{'id':'csmbol_date_'+box_number});
			var date_cap_div = new Element('div.csmbol-date-caption',{'text':'Event Date:'});
			var cal_div = new Element('div'); var cal_prev_date = new Element('input',{id:'inp_cal_prev_date_'+box_number,'type':'hidden'});				
			var cal_id = 'id_cal_'+box_number;
			var cal_img_src = '../components/com_csmbol/images/calendar.png';
			var cal_input = new Element('input.ro',{'type':'text','name':'event_date','id':cal_id,size:'10 px',readonly:'readonly'}); 
			var cal_img = new Element('img',{'src':cal_img_src, 'value':'','id':cal_id+'_img', 
			events:{click:function(){
							//click the cal img switches the showing state of the picker
							pickershowing = !pickershowing;
							if(pickershowing){ 
								disableTab(tab_add_options);
								disableTab($('tab_booking_summary'));
								disableBtn(btn_sd_add_options);
							}else if(box_option_timing_container.getFirst() != null){//not empty){
								enableBtn(btn_sd_add_options);
								enableTab($('tab_booking_summary'));
								enableTab(tab_add_options);
							}							
						  	displayDatePicker(cal_id, this);
						  }
					}
				});
			cal_div.adopt(cal_input,cal_img);
						
			var room_sel = new Element('select.csmbol-inp', {id:'sd_room_sel_'+box_number, name:'event_room', styles:{float: 'left', width: '110px', 'margin-top': '5px'}});
			var room_prev_sel = new Element('input',{id:'inp_room_prev_sel_'+box_number,'type':'hidden'});
			
			//room_sel.disabled = true;
			room_sel.addClass('csmbol-inp');			
			//populate rooms
			room_sel.grab( new Element('option', {value:'action_room', text:'Action Room'}));
			room_sel.grab( new Element('option', {value:'passion_room', text:'Passion Room'}));	
			if(isStaff(user_group)){
				room_sel.grab( new Element('option', {value:'genius_room', text:'Genius Room'}));
				room_sel.grab( new Element('option', {value:'elite_room', text:'Elite Room'}));
				room_sel.grab( new Element('option', {value:'focus_room', text:'Focus Room'}));				
				room_sel.grab( new Element('option', {value:'wisdom_room', text:'Wisdom Room'}));	
				room_sel.grab( new Element('option', {value:'harmony_room', text:'Harmony Room'}));					
				room_sel.grab( new Element('option', {value:'spirit_room', text:'Spirit Room'}));											
			}
			room_prev_sel.value = 'action_room';
			
			room_sel.addEvent('change', function(event){
				event.stop();
				if(cal_input.get('value')!=''){
					if(!declinedDateRoom($('id_cal_'+box_number).value, this.value, box_number) ){
						if( $('csmbol-timebox-'+box_number) != null)
							$('csmbol-timebox-'+box_number).destroy();
						showAvailability(box_number);					
						$('inp_room_prev_sel_'+box_number).value = this.value;
					}
					else{
						this.value = $('inp_room_prev_sel_'+box_number).value; 
					}
				}
			});
			
			date_div.adopt(date_cap_div, cal_div,cal_prev_date, room_sel, room_prev_sel);
			
			//service module
			var serv_module = new Element('div',{'id':'csmbol-service-module'});
			var serv_module_id = new Element('div.csmbol-datetimebox-running-number',{'id':'box_id_'+box_number,'html':'#'+box_number});
			var serv_module_btn = new Element('input.csmbol-btn',{'type':'button','name':'remove_date','value':'X','id':'btn_remove_date','name':'remove_date'}); 
			$(serv_module_btn).addEvent('click',function(event){
				event.stop();
				removeDate(box_number)
			});
			serv_module.adopt(serv_module_id,serv_module_btn);

			//attach public holiday info
			var inp_ph = new Element('input',{'id':'inp_ph_'+box_number,'type':'hidden', 'value':'none'});			
			datetimebox.adopt(date_div, serv_module);
			datetimebox.grab(inp_ph);
			//register the date field onchange event 
			var date_field_id = 'id_cal_'+box_number;
			$(date_field_id).addEvent('change', function(event){
				event.stop();
				
				pickershowing = false;
				if(box_option_timing_container.getFirst() != null){//not empty){				
					//date picker closed, enable next step
					enableTab(tab_add_options);
					//enableTab($('tab_booking_summary'));
					enableBtn(btn_sd_add_options);
				}
				if(!declinedDateRoom(this.value, $('sd_room_sel_'+box_number).value, box_number)){	
					$('inp_cal_prev_date_'+box_number).value = this.value;					
					if( $('csmbol-timebox-'+box_number) != null)
						$('csmbol-timebox-'+box_number).destroy();
					showAvailability(box_number);					
					if(box_option_timing_container.getFirst() == null){//empty){
						disableBtn(btn_sd_add_options);
						disableTab(tab_add_options);
						disableTab($('tab_booking_summary'));
					}
				}else this.value = $('inp_cal_prev_date_'+box_number).value;
			});
			//inject done
			nodtb++;global_box_id++;	
		}else window.alert('You can add up to '+nodtb_max+' dates in one booking session.');
	});
	
});

function startNewBookingSession(response){
	
	if(isEventOrganizer(user_group)) booking_status = 'client_in_progress';
	if(isStaff(user_group)) booking_status = 'admin_in_progress';

	enableFunctions();						
	if(isStaff(user_group)){
		if($('tab_at')==null){
			addAdminToolPage();	
		}
		if($('btn_admin_book_now')==null){
			//add 'Make Admin Booking' button
			var admin_booking_button = new Element('input.csmbol-btn.disabled',{'type':'button', 'id':'btn_admin_book_now', 'value':"Admin Book Now"});
			admin_booking_button.addEvent('click', function(){makeAdminBookingNow();}); 
			$('csmbol-booking-rightcolumn-inner').grab(admin_booking_button);//add the admin booking button
		}
		btn_ppbtn_div.setStyle('display','none');//hide the paypal button	
		disableBtn(btn_bc_new_booking);
		disableBtn($('btn_admin_book_now'));					
	}				
	if(isStaff(user_group)||isEventOrganizer(user_group)){	
		disableBtn(btn_sd_add_options);						
		disableBtn(btn_bn_restart_booking);
		addFirstDateTimeBox(true, true);
		var rates = {}; rates = response.rates;
		
		assignRates(response.rates);
	}
	btn_ppbtn_div.getElement('input[name=return]').set('value',response.pp_return);	
	btn_ppbtn_div.getElement('input[name=cancel_return]').set('value',response.pp_cancel);	
	
	gotoDatePage();	
};

function declinedDateRoom(date, room, box_id){
	var declinedDate = false;
	if(date != ''){
		var msg = '';
		var cur_box = $('csmbol-datetimebox-'+box_id);
		var datetimeboxes = $$('.csmbol-datetimebox');
		datetimeboxes.some(function(datetimebox, index){
			if(datetimebox.id != cur_box.id){
				old_box_id = datetimebox.id.replace('csmbol-datetimebox-','');
				if( ($('id_cal_'+old_box_id).value == date) && ($('sd_room_sel_'+old_box_id).value == room) ){
					declinedDate = true;
					msg = 'Date/Room already selected in #'+old_box_id+', please select another date.';	
					window.alert(msg);
					return declinedDate;//use some..return to break each() loop early
				}else return false;
			}			
		});
		//future date only
		if(!declinedDate){
			var selected_date=new Date(date.replace(/-/g,'/'));
			var today = new Date();
			today.setDate(today.getDate()-1);	
			if(!isStaff(user_group)){//only staff can select previous dates		
				if (selected_date<today){
					declinedDate = true;
					msg = 'Please select a future date.';
					window.alert(msg);			
				}
			}
		}
	}else declinedDate = true;
	return declinedDate;
}
function isStaff(user_group){
	if(user_group['super_user']||user_group['admin']||user_group['manager']||user_group['csm_booking_admin'])
		return true;
	else return false;
};
function isAdmin(user_group){
	if(user_group['super_user']||user_group['admin'])
		return true;
	else return false;
};

function isEventOrganizer(user_group){
	if(user_group['event_organizer'])
		return true;
	else return false;	
};
function disableFunctions(){
	disableTab($('tab_select_date'));
	disableTab($('tab_add_options'));
	disableTab($('tab_booking_summary'));
	disableTab($('tab_book_now'));
	disableTab($('tab_complete'));
	disableBtn(btn_sd_add_date);
	disableBtn(btn_sd_add_options);	
	disableBtn(btn_sd_clear_dates);	
};
function enableFunctions(){
	enableTab($('tab_select_date'));	
	enableBtn(btn_sd_add_date);
//	enableBtn(btn_sd_add_options);	
	enableBtn(btn_sd_clear_dates);		
}
function showRegistration(){
	box_datetimebox_container.empty();
	
	var organizer_reg_info_box = new Element('div.csmbol-info-box.csmbol-error',{'text':'User authentication required to use the online booking system.'})
	var organizer_reg_ul = new Element('ul');
	var organizer_reg_ol1 = new Element('ol',{'text':'* Verified organizers, please log in.'});
	var organizer_reg_ol2 = new Element('ol',{'text':'* Newly registered users, please contact us at 6338 0566 or enquiry@csm.sg for verification.'});
	organizer_reg_ul.adopt(organizer_reg_ol1,organizer_reg_ol2);
	organizer_reg_info_box.grab(organizer_reg_ul);
	box_datetimebox_container.grab(organizer_reg_info_box);	
};	 
function addAdminToolPage(){
	var at_tab = new Element('li.csmbol-tab',{id:'tab_at','text':'AT',styles:{width:'50px'}});
	$('csmbol-tabs-id').grab(at_tab);	

	var csmbol_tabs = $$('.csmbol-tabs LI.csmbol-tab'),
    csmbol_content = $$('.csmbol-tabcontent');

	at_tab.addEvent('click', function(event){
		event.stop();
		csmbol_tabs.removeClass('selected');
		csmbol_content.removeClass('selected');
		at_tab.addClass('selected');
		$('tab_at_content').addClass('selected');
	});
}; 

function assignRates(rates){
	var room = 'action_room';
	for(i=0;i<nor;i++){
		switch(i){
			case 0:
			room = 'action_room';break;
			case 1:
			room = 'passion_room';break;
			case 2:
			room = 'genius_room';break;
			case 3:
			room = 'elite_room';break;
			case 4:
			room = 'focus_room';break;			
			case 5:
			room = 'wisdom_room';break;
			case 6:
			room = 'harmony_room';break;
			case 7:
			room = 'spirit_room';break;									
			default:
			room = 'action_room';break;
		}
		rate_weekday_am[room] = rates[room]['rate_weekday_am'];
		rate_weekday_pm[room] = rates[room]['rate_weekday_pm'];
		rate_weekday_ev[room] = rates[room]['rate_weekday_ev'];
		rate_weekend_am[room] = rates[room]['rate_weekend_am'];
		rate_weekend_pm[room] = rates[room]['rate_weekend_pm'];
		rate_weekend_ev[room] = rates[room]['rate_weekend_ev'];
		
		rate_mon_am[room] = rates[room]['rate_mon_am'];
		rate_mon_pm[room] = rates[room]['rate_mon_pm'];
		rate_mon_ev[room] = rates[room]['rate_mon_ev'];
		rate_tue_am[room] = rates[room]['rate_tue_am'];
		rate_tue_pm[room] = rates[room]['rate_tue_pm'];
		rate_tue_ev[room] = rates[room]['rate_tue_ev'];
		rate_wed_am[room] = rates[room]['rate_wed_am'];
		rate_wed_pm[room] = rates[room]['rate_wed_pm'];
		rate_wed_ev[room] = rates[room]['rate_wed_ev'];
		rate_thu_am[room] = rates[room]['rate_thu_am'];
		rate_thu_pm[room] = rates[room]['rate_thu_pm'];
		rate_thu_ev[room] = rates[room]['rate_thu_ev'];
		rate_fri_am[room] = rates[room]['rate_fri_am'];
		rate_fri_pm[room] = rates[room]['rate_fri_pm'];
		rate_fri_ev[room] = rates[room]['rate_fri_ev'];
		rate_sat_am[room] = rates[room]['rate_sat_am'];
		rate_sat_pm[room] = rates[room]['rate_sat_pm'];
		rate_sat_ev[room] = rates[room]['rate_sat_ev'];
		rate_sun_am[room] = rates[room]['rate_sun_am'];
		rate_sun_pm[room] = rates[room]['rate_sun_pm'];
		rate_sun_ev[room] = rates[room]['rate_sun_ev'];
	}						
		
	//timing options
	rate_opt_15min = rates['rate_opt_15min']; //extention time
	//visual options
	rate_opt_pws = rates['rate_opt_pws']; //projector with screen
	rate_opt_so = rates['rate_opt_so']; //screen only
	rate_opt_fcwp = rates['rate_opt_fcwp']; //flipchart with paper
	rate_opt_fcm = rates['rate_opt_fcm']; //flipchart marker
	rate_opt_wb = rates['rate_opt_wb']; //white board wiht marker
	//audio options
	rate_opt_mic_co = rates['rate_opt_mic_co']; //mic clip-on with audio system
	rate_opt_mic_hh = rates['rate_opt_mic_hh']; //mic hand-held with audio system
	rate_opt_aso = rates['rate_opt_aso']; //audio system only
	rate_opt_ms = rates['rate_opt_ms'];	//mic stand	
	//connection options
	rate_opt_wic = rates['rate_opt_wic']; //wireless internet connection
	rate_opt_wnt = rates['rate_opt_wnt']; //wireless NETS terminal
	//layout options
	rate_opt_tbl = rates['rate_opt_tbl']; //table
	rate_opt_layout = rates['rate_opt_layout']; //layout
	//public holiday
	rate_opt_ph = rates['rate_opt_ph'];
	
	rate_surcharge = rates['rate_surcharge'];
};
//clear all existing datetime boxes and session store, then add a new one
function clearDates(add_first_datetime_box){
	disableTab(tab_add_options);
	disableTab($('tab_booking_summary'));
	disableBtn(btn_sd_add_options);
	
	box_datetimebox_container.empty();
	new Request.JSON({
		//clearDates() will also clear session store and reset booking_status to client_in_progress
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=clearDates&format=raw',
		onRequest: function(){
			box_datetimebox_container.empty();
			box_option_timing_container.empty();
			nodtb = 0;
			global_box_id = 0;
		},
		onComplete: function(response){
			if(add_first_datetime_box)
				addFirstDateTimeBox(false, true);
		}
	}).send();
};

function clearBooking(add_first_datetime_box){
	clearDates(add_first_datetime_box);

	disableTab(tab_add_options);
	disableTab($('tab_booking_summary'));	
	disableBtn(btn_sd_add_options);
	disableBtn(btn_bn_restart_booking);
	disableBtn(btn_bc_new_booking);
	btn_ppbtn_div.setStyle('display','none');
	
	if(booking_status == 'admin_in_progress')			
		disableBtn($('btn_admin_book_now'));	
			
	box_option_timing_container.empty();
	box_booking_summary_container.empty();
	box_book_now_container.empty();
	box_complete_container.empty();			
	if(box_client_info_container){
		box_client_info_container.destroy();
		box_client_info_container=null; //global var, must set to null or it will stil exist
	}
};

function makeNewBooking(){
//	global_countdown_stop = true;
	
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=iniBooking&format=raw',
		onRequest: function(){
		},
		onComplete: function(response){
/*			var rates = {}; rates = response.rates;
			assignRates(response.rates);
*/			
//			clearBooking(true);//clear and add first datetimebox
			clearBooking(false); //clear
			
			startNewBookingSession(response);			
			
			
/*			if(isEventOrganizer(user_group)) booking_status = 'client_in_progress';
			if(isStaff(user_group)) booking_status = 'admin_in_progress';
			if((booking_status == 'admin_in_progress')||(booking_status == 'client_in_progress')){

				btn_ppbtn_div.getElement('input[name=return]').set('value',response.pp_return);	
				btn_ppbtn_div.getElement('input[name=cancel_return]').set('value',response.pp_cancel);						

				enableFunctions();		
			}

			gotoDatePage();	
*/		}
	}).send(/*'current_room='+current_room*/);		
};

function addFirstDateTimeBox(goto_date_page, addColorIndicator){
	
	disableTab($('tab_add_options'));
	disableTab($('tab_booking_summary'));
	disableTab($('tab_book_now'));
	disableTab($('tab_complete'));

	var btn_addDate = $('btn_sd_add_date');
	var csmbol_tabs = $$('.csmbol-tabs LI.csmbol-tab');
	if(goto_date_page)
		csmbol_tabs[0].fireEvent('click', {target: csmbol_tabs[0], stop: $empty}); //display the first tab on startup
	btn_addDate.fireEvent('click', {target: btn_addDate, stop: $empty}); //fire click event to add first datetimebox	
};

function chkSession(){
	var session_exists = false;
			
	var overlay = new Overlay(document.body,{
			id: 'overlay',
			color: '#000',
			duration: 300,
			opacity: 0.4,
			onClick: function() {
				this.close();
			},
			onOpen: function() {
				//make ajax call while the overlay is happening...?
				//var Request = new Request()....
				new Request.JSON({
					url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=checkSession&format=raw',
					onRequest: function(){
					},
					onComplete: function(response){
					   window.alert('success!');
					   session_exists = response.session_exists;
					   return session_exists;
					}
				}).send();																
			}
	});	
	overlay.open();
};

function showFirstDateTimeBox(){
	var btn_addDate = $('btn_sd_add_date');	
	var csmbol_tabs = $$('.csmbol-tabs LI.csmbol-tab');
	csmbol_tabs[0].fireEvent('click', {target: csmbol_tabs[0], stop: $empty}); //display the first tab on startup
	btn_addDate.fireEvent('click', {target: btn_addDate, stop: $empty}); //fire click event to add first datetimebox
};

function disableTab(the_tab){
	the_tab.addClass('disabled');	
	the_tab.removeEvents('click');			
	switch (the_tab.id) {
	case 'tab_select_date':
		tab_date_enabled = false;
	break;
	case 'tab_add_options':
		tab_option_enabled = false;
	break;
	case 'tab_booking_summary':
		tab_summary_enabled = false;
	break;
	case 'tab_book_now':
		tab_booking_enabled = false;	
	break;		
	}
}
function enableTab(the_tab){
	the_tab.removeClass('disabled');	
	var csmbol_tabs = $$('.csmbol-tabs LI.csmbol-tab'),
    csmbol_content = $$('.csmbol-tabcontent');	
	the_tab.addEvent('click', function(event){
		event.stop();
		csmbol_tabs.removeClass('selected');
		csmbol_content.removeClass('selected');
		the_tab.addClass('selected');
		$(the_tab.get('id')+'_content').addClass('selected');
		
		switch (the_tab.id) {
		case 'tab_select_date':
			tab_date_enabled = true;
			break;			
		case 'tab_add_options':
			tab_option_enabled = true;
			if((booking_status == 'admin_in_progress')||(booking_status == 'client_in_progress'))
				if(!box_client_info_container)
					genClientInfoOptions(booking_status);	
			break;		
		case 'tab_booking_summary':
			tab_summary_enabled = true;
			genBookingInfo(true);
			break;		
		case 'tab_book_now':
			tab_booking_enabled = true;	
		break;					
		}
	});			
}
function disableBtn(the_btn){
	if(the_btn){
		the_btn.addClass('disabled');	
		the_btn.disabled=true;			
	}
}
function enableBtn(the_btn){
	if(the_btn){
		the_btn.removeClass('disabled');
		the_btn.disabled=false;		
	}
}
function gotoDatePage(){
	var the_tab = $('tab_select_date');
	if(!tab_date_enabled)	
		enableTab(the_tab);
	the_tab.fireEvent('click', {target: the_tab, stop: $empty});
};

function gotoOptionPage(){
	
	if((booking_status == 'admin_in_progress')||(booking_status == 'client_in_progress'))
		if(!box_client_info_container)
			genClientInfoOptions(booking_status);	
	var the_tab = tab_add_options
	if(!tab_option_enabled)	
		enableTab(the_tab);	
	the_tab.fireEvent('click', {target: the_tab, stop: $empty}); 	
};

function gotoSummaryPage(){
	var valid = true;
	if($('client_email'))
		if(!checkEmail($('client_email').get('value'))) valid = false;
	if($('client_phone'))
		if(!checkPhone($('client_phone').get('value'))) valid = false;		
		
	for(i=1;i<=nodtb_max;i++){
		var title = 'csmbol-option-eventtitle-'+i;	
		if($(title)){
			if(($(title).get('value')==title_indicator)||($(title).get('value')=='')){
				valid = false;	
				window.alert('Please fill in event title.');
				i=nodtb_max;
			}			
			else{
				var title2 = title+'e';
				if($(title2)){
					if(($(title2).get('value')==title_indicator)||($(title2).get('value')=='')){
						valid = false;				
						window.alert('Please fill in event title.');
						i=nodtb_max;
					}
				}
			}
		}
	}	
	if(valid){	
		var the_tab = $('tab_booking_summary');	
		if(!tab_summary_enabled)
			enableTab(the_tab);
		the_tab.fireEvent('click', {target: the_tab, stop: $empty});
	}	
};

function gotoBookingPage(){
	//disable all previous tabs, no backward beyond this point
	disableTab($('tab_select_date'));
	disableTab($('tab_add_options'));		
	disableTab($('tab_booking_summary'));	

	var the_tab = $('tab_book_now');	
	if(!tab_booking_enabled)		
		enableTab(the_tab);
	the_tab.fireEvent('click', {target: the_tab, stop: $empty}); 
	
	enableBtn(btn_bn_restart_booking);
			
	var booking_sum = $('id_booking-sum').get('value');

	var pp_booking_sum = document.getElement('input[name=amount]');
	pp_booking_sum.value = roundNumber(booking_sum, 2);
	var booking_num = genBookingNumber();
	var pp_booking_num = document.getElement('input[name=item_number]');
	pp_booking_num.value = "obp_"+booking_num;						
};

function gotoCompletedPage(){
	//disable all other tabs
	disableTab($('tab_select_date'));
	disableTab($('tab_add_options'));
	disableTab($('tab_booking_summary'));
	disableTab($('tab_book_now'));
	
	var the_tab = $('tab_complete');	
	enableTab(the_tab);
	the_tab.fireEvent('click', {target: the_tab, stop: $empty});
};

function genClientInfoOptions(booking_status){
	var titlediv = new Element('div.csmbol-option-title',{'text':'Client Information'});

	if(booking_status == 'admin_in_progress'){
		var optiondiv_client_name = new Element('div.csmbol-option');	
		var itemdiv_client_name = new Element('div',{'width':'98%','text':'Client Name '});
		var item_client_name = new Element('input.csmbol-inp', {'id':'client_name','maxlength':'80'});
		itemdiv_client_name.grab(item_client_name);
		optiondiv_client_name.grab(itemdiv_client_name);
	
		var optiondiv_client_company = new Element('div.csmbol-option');	
		var itemdiv_client_company = new Element('div',{'width':'98%','text':'Company Name '});
		var item_client_company = new Element('input.csmbol-inp', {'id':'client_company','maxlength':'80'});
		itemdiv_client_company.grab(item_client_company);
		optiondiv_client_company.grab(itemdiv_client_company);
		
		var optiondiv_client_email = new Element('div.csmbol-option');	
		var itemdiv_client_email = new Element('div',{'width':'98%','text':'Client Email '});
		var item_client_email = new Element('input.csmbol-inp', {'id':'client_email','maxlength':'80'});
		itemdiv_client_email.grab(item_client_email);
		optiondiv_client_email.grab(itemdiv_client_email);
	}
	
	var optiondiv_client_phone = new Element('div.csmbol-option');	
	var itemdiv_client_phone = new Element('div',{'width':'98%','text':'Contact Person\'s Direct Singapore Mobile '});
	var item_client_phone = new Element('input.csmbol-inp', {'id':'client_phone','maxlength':'15'});
	itemdiv_client_phone.grab(item_client_phone);
	optiondiv_client_phone.grab(itemdiv_client_phone);
	
	box_client_info_container = new Element('div',{id:'box_client_info_container'});
	if(booking_status == 'admin_in_progress'){	
		box_client_info_container.grab(optiondiv_client_company, 'top');
		box_client_info_container.grab(optiondiv_client_phone, 'top');	
		box_client_info_container.grab(optiondiv_client_email, 'top');	
		box_client_info_container.grab(optiondiv_client_name, 'top');		
		box_client_info_container.grab(titlediv, 'top');	
	}else{
		box_client_info_container.grab(optiondiv_client_phone, 'top');
		box_client_info_container.grab(titlediv, 'top');			
	}
	
	$('csmbol-option-box').grab(box_client_info_container,'top');
};
function removeOptions(box_id){
}

function updateTimingTitleOption(input_id){

	var datetimebox_id = input_id.replace("slot_am_","csmbol-datetimebox-");
	datetimebox_id = datetimebox_id.replace("slot_pm_","csmbol-datetimebox-");	
	datetimebox_id = datetimebox_id.replace("slot_ev_","csmbol-datetimebox-");		
	datetimebox_id = datetimebox_id.replace("slot_fc_","csmbol-datetimebox-");
	var box_id = datetimebox_id.replace("csmbol-datetimebox-","");//the index, not the element id			
	var day = $(datetimebox_id); //note: $$('#id') only gets the first element instead of a group with the same id
	//get date time
	var event_date = day.getElement('input[name=event_date]').get('value');//the date string
	var event_room = day.getElement('select[name=event_room]').get('value');//the date string	

	if(event_date != ""){
		var booking_slot_info = genBookingSlotInfo(day);
		var slot = booking_slot_info['slot'];
		var slot_flag = booking_slot_info['slot_flag'];

		var session_slots = booking_slot_info['session_slots'];//number of slots of a session (1,2,3)
	}
	//gen the timing optins in a select
	var	early_step = 1;
	var	extend_step = 1;

	switch (String(slot_flag)){
		case 'slot_am':
		early_step = early_step_am;
		extend_step = extend_step_am;
		break;
		case 'slot_pm':
		early_step = early_step_pm;
		extend_step = extend_step_pm;
		break;
		case 'slot_ev':
		early_step = early_step_ev;
		extend_step = extend_step_ev;
		break;
		case 'slot_fd1':
		early_step = early_step_am;
		extend_step = extend_step_pm;
		break;
		case 'slot_fd2':
		early_step = early_step_pm;
		extend_step = extend_step_ev;
		break;			
		case 'slot_cd':
		early_step = early_step_am;
		extend_step = extend_step_ev;
		break;
		default:
		break;
	};	

	if((slot_flag != 'slot_ae')&&(slot_flag!='slot_empty')){
		var select_start_id = 'csmbol-select-start-'+ box_id;
		var select_end_id = 'csmbol-select-end-'+ box_id;
		if($('csmbol-option-timing-'+box_id)) $('csmbol-option-timing-'+box_id).destroy();
		if($('csmbol-option-timing-'+box_id+'e')) $('csmbol-option-timing-'+box_id+'e').destroy();
		if($('csmbol-option-ph-'+ box_id + 'e')) $('csmbol-option-ph-'+ box_id + 'e').destroy();
		updateTimingSelectOptions(event_date, event_room, select_start_id, select_end_id, early_step, extend_step, slot_flag, box_id, '');
	}else if (slot_flag == 'slot_ae'){//slot_ae
		var select_start_id = 'csmbol-select-start-'+ box_id;
		var select_end_id = 'csmbol-select-end-'+ box_id;
		updateTimingSelectOptions(event_date, event_room, select_start_id, select_end_id, early_step_am, extend_step_am, 'slot_am', box_id, '');
		var select_start_id = 'csmbol-select-start-'+ box_id +'e';
		var select_end_id = 'csmbol-select-end-'+ box_id +'e';
		updateTimingSelectOptions(event_date, event_room, select_start_id, select_end_id, early_step_ev, extend_step_ev, 'slot_ev', box_id, 'e');
	}else{//slot_empty
		removeDateTimingOptioins(box_id)
	};
	
	if(box_option_timing_container.getFirst() != null){//empty
		enableBtn(btn_sd_add_options);
		enableTab(tab_add_options);
	}
	else{ 
		disableBtn(btn_sd_add_options);
		disableTab(tab_add_options);		
		disableTab($('tab_booking_summary'));		
	}
};
function getRoomTitle(room){
	var title;
	switch(room){
		case 'action_room':
			title = 'Action Room';
			break;
		case 'passion_room':
			title = 'Passion Room';	
			break;
		case 'genius_room':
			title = 'Genius Room';	
			break;
		case 'elite_room':
			title = 'Elite Room';
			break;
		case 'focus_room':
			title = 'Focus Room';
			break;			
		case 'wisdom_room':
			title = 'Wisdom Room';
			break;
		case 'harmony_room':
			title = 'Harmony Room';
			break;
		case 'spirit_room':
			title = 'Spirit Room';
			break;												
		default: title = 'Action Room';		
	}
	return title;
}

function updateTimingSelectOptions(event_date, event_room, select_start_id, select_end_id, early_step, extend_step, slot_flag, box_id, ext){
	var timing_select_start = $(select_start_id);
	var timing_select_end = $(select_end_id);		
	var newrow = false;
	if(!timing_select_start){
		var timing_select_start = new Element('select.csmbol-inp', {id:select_start_id, styles:{float: 'left', width: '70px'}});			
		var timing_select_end = new Element('select.csmbol-inp', {id:select_end_id, styles:{float: 'left', width: '70px'}});
		newrow = true;
	}else{	
		timing_select_start.empty();
		timing_select_end.empty();	
	};	
	
	var step_more = 20;
	if(!isStaff(user_group)){
		step_more = 0;
	}
	
	if(isStaff(user_group)){
		switch (String(slot_flag)){
			case 'slot_am':
			hour_start = hour_start_am;
			hour_end = hour_end_am;
			minute_start = minute_start_am;
			minute_end = minute_end_am;
			break;
			case 'slot_pm':
			hour_start = hour_start_pm;
			hour_end = hour_end_pm;
			minute_start = minute_start_pm;
			minute_end = minute_end_pm;
			break;
			case 'slot_ev':
			hour_start = hour_start_ev;
			hour_end = hour_end_ev;
			minute_start = minute_start_ev;
			minute_end = minute_end_ev;
			break;
			case 'slot_fd1':
			hour_start = hour_start_am;
			hour_end = hour_end_pm;
			minute_start = minute_start_am;
			minute_end = minute_end_pm;
			break;
			case 'slot_fd2':
			hour_start = hour_start_pm;
			hour_end = hour_end_ev;
			minute_start = minute_start_pm;
			minute_end = minute_end_ev;
			break;			
			case 'slot_cd':
			hour_start = hour_start_am;
			hour_end = hour_end_ev;
			minute_start = minute_start_am;
			minute_end = minute_end_ev;
			break;
			default:
			window.alert('start time end time error');
			break;
		}
		
		//populate the list		
		hour = 7;
		minute = 0;
		
		for(i=0;i<68;i++){
			var minute_text = minute;
			if(minute == 60 ){
				minute_text = "00";
				hour += 1;
				minute = 0;				
			}
			
			var hour_text = hour;
			if(hour<10)	hour_text = "0"+hour_text;
						
			if(minute == 0)
				minute_text = "00";
			var start = new Element('option', {value:i, text:hour_text+':'+minute_text});	
			timing_select_start.grab(start);
			if((hour == hour_start/*-1*/)&&(minute == minute_start/*+30*/)) start.selected = true; 
			var end =  new Element('option', {value:i, text:hour_text+':'+minute_text});
			timing_select_end.grab(end);	
			if((hour == hour_end)&&(minute == minute_end/*+30*/)) end.selected = true;			
			
			minute += 15;	
		}
	}else{
		for(i=0;i<early_step+step_more;i++){
			var startendtime = genStartEndTime(slot_flag, i, extend_step);		
			timing_select_start.grab( new Element('option', {value:i, text:startendtime['starttime']}));				
		}
		for(i=0;i<extend_step+step_more;i++){
			var startendtime = genStartEndTime(slot_flag, early_step, i);	
			timing_select_end.grab( new Element('option', {value:i, text:startendtime['endtime']}));			
		}
	}
	
	var ph_row = $('csmbol-option-ph-'+ box_id + ext);
	if(ph_row) ph_row.destroy();
		
	var ph = $('inp_ph_'+box_id).get('value'); var timing_ph_row= null;
	if(ph != 'none'){
		if(!$('csmbol-option-ph-'+ box_id + ext))
			timing_ph_row = new Element('div.csmbol-option', {'id':'csmbol-option-ph-'+ box_id + ext, 'html':'Public Holiday: '+ph, styles:{float: 'left','font-weight':'bold'}});
	}
	if(newrow){
		//title
		var div_optf_title_options = new Element('div.csmbol-option-title', {'id':'csmbol-option-title-options-'+ box_id + ext, 'text':'Event Title and Booking Options for '+event_date+' in '+getRoomTitle(event_room), styles:{float: 'left',background:'#DAEADA'}});		
		var timing_option_row = new Element('div.csmbol-option', {'id':'csmbol-option-timing-'+ box_id + ext, styles:{float: 'left'}});
		timing_option_eventdate = new Element('div', {'id':'csmbol-option-eventdate-'+ box_id + ext,'text':event_date, styles:{float: 'left', width: '70px'}});		
		title = new Element('input.csmbol-inp', {'id':'csmbol-option-eventtitle-'+ box_id + ext,'maxlength':'80', styles:{float: 'left', width: '330px', color:'#AAA'}, events: {click: function(){this.value = ""; this.setStyle('color','#000'); this.removeEvents('click');}/*, keyup: function(){$('opt_sfas_e').disabled = false; }*/} });
		title.set('value', title_indicator);			
		timing_option_row.adopt(timing_option_eventdate, timing_select_start, timing_select_end, title);		
		
		var options_div = genOptionField(box_id, ext, event_room, event_date, slot_flag);
		timing_option_row.grab(div_optf_title_options,'top');
		timing_option_row.grab(options_div);		
		options_div.setStyle('display','none');
		//toggler
		var a_options = new Element('a',{'id':'csmbol-option-t-'+ box_id + ext,text:' [+] show options', styles:{cursor:'pointer'}}); 
		var a_options_toggler = new Element('input',{type:'hidden',value:0});
		a_options.grab(a_options_toggler);
		a_options.addEvent('click',
		function(event){
			event.stop();
			if(a_options_toggler.get('value') == 0){//hidden
				options_div.setStyle('display','inherit');
				a_options.set('text',' [-] hide options');
				a_options_toggler.set('value', 1);
			}else{
				options_div.setStyle('display','none');
				a_options.set('text',' [+] show options');
				a_options_toggler.set('value', 0);				
			}
		});
		div_optf_title_options.grab(a_options);		

		if(ext == 'e'){//evening slot
			if($('csmbol-option-timing-'+box_id)){
				$('csmbol-option-timing-'+box_id).grab(timing_option_row,'after') ;
			}
		}else{ 	//sort to place the new row in order
			box_option_timing_container.grab(timing_option_row);
			var sessions = box_option_timing_container.getChildren();
			sessions.some(function(session, index){ 
				var id = session.id.replace('csmbol-option-timing-','');
				if(box_id<id){
					session.grab(timing_option_row,'before');
					return true;
				}else return false;
			});
		}
		if(timing_ph_row) timing_option_row.grab(timing_ph_row,'before');
			
	}else{
		$('csmbol-option-eventdate-'+ box_id + ext).set('text',event_date);
	}
	
	if(ph=='none'){
		var timing_ph_row = $('csmbol-option-ph-'+ box_id + ext);
		if(timing_ph_row){
			timing_ph_row.destroy();
		}
	}else if(timing_ph_row) $('csmbol-option-timing-'+ box_id + ext).grab(timing_ph_row,'before'); 	
};

function removeDateTimingOptioins(box_id){
	var timing_ap_id = 'csmbol-option-timing-'+box_id;		
	var timing_ap = $(timing_ap_id);
	var timing_e = $(timing_ap_id+'e');
	var	ph_row = $('csmbol-option-ph-'+box_id);		
	var	ph_row_e = $('csmbol-option-ph-'+box_id+'e');		

	if(timing_ap) timing_ap.destroy();		
	if(timing_e) timing_e.destroy();
	if(ph_row) ph_row.destroy();
	if(ph_row_e) ph_row_e.destroy();			
};
//Timing/Visual/Audio/Connect for selection
function genOptionField(box_id, ext, event_room, event_date, slot_flag){
	//option container div
	var div_option_field = new Element('div', {'id':'csmbol-option-field-'+ box_id + ext, styles:{float: 'left','width':'100%'}});
	//visual options
	//title
	var div_optf_title_visual = new Element('div.csmbol-option-title', {'id':'csmbol-option-title-visual-'+ box_id + ext, 'text':'Visual Options', styles:{float: 'left'}});
	//projector and screen
	var div_optf_pws = new Element('div.csmbol-option', {'text':' Projector and Screen', styles:{float: 'left', width: '93%', }});
	
//	var div_optf_so = new Element('div.csmbol-option', {'text':' Screen Only', styles:{float: 'left', width: '65%'}});//screen only	
	var inp_optf_pws = new Element('input',{'id':'csmbol-optf-pws-'+ box_id + ext, 'type':'checkbox','name':'opt_pws'});
//	var inp_optf_so = new Element('input',{'id':'csmbol-optf-so-'+ box_id + ext, 'type':'checkbox','name':'opt_so'});	
	div_optf_pws.grab(inp_optf_pws,'top');
//	div_optf_so.grab(inp_optf_so,'top');	
//	inp_optf_pws.addEvent('click', function(){inp_optf_so.disabled = inp_optf_pws.checked;});	
//	inp_optf_so.addEvent('click', function(){inp_optf_pws.disabled = inp_optf_so.checked;});	
	inp_optf_pws.checked = true;
	//flip chart
	var div_optf_fcwp = new Element('div.csmbol-option', {'text':' Flip Chart (with 25pcs paper)'});
	var sel_optf_fcwp = new Element('select.csmbol-inp',{'id':'csmbol-optf-fcwp-'+ box_id + ext, 'name':'opt_pws'});
	div_optf_fcwp.grab(sel_optf_fcwp,'top');

	sel_optf_fcwp.grab( new Element('option', {value:0, text:'Not Selected'}));	
	sel_optf_fcwp.grab( new Element('option', {value:1, text:'1'}));	
	sel_optf_fcwp.grab( new Element('option', {value:2, text:'2'}));	
	//flip chart marker
//	var div_optf_fcm = new Element('div.csmbol-option', {'text':' Flipchart marker set'});
//	var inp_optf_fcm = new Element('input',{'id':'csmbol-optf-fcm-'+ box_id + ext, 'type':'checkbox', 'name':'opt_fcm'});
//	div_optf_fcm.grab(inp_optf_fcm,'top');		
//	sel_optf_fcwp.addEvent('change', function(){if(sel_optf_fcwp.value == '0'){ inp_optf_fcm.checked = false;}else{inp_optf_fcm.checked = true;}});		
	//white board with marker
//	var div_optf_wb = new Element('div.csmbol-option', {'text':' White Board with white board marker'});
//	var inp_optf_wb = new Element('input',{'id':'csmbol-optf-wb-'+ box_id + ext, 'type':'checkbox', 'name':'opt_wb'});
//	div_optf_wb.grab(inp_optf_wb,'top');
	//audio options
	//title
	var div_optf_title_audio = new Element('div.csmbol-option-title', {'id':'csmbol-option-title-audio-'+ box_id + ext, 'text':'Audio Options', styles:{float: 'left'}});
	//mic
	var div_optf_mic_co = new Element('div.csmbol-option', {'text':' Wireless Microphone-Clip-on + Audio System'});
	var sel_optf_mic_co = new Element('select.csmbol-inp',{'id':'csmbol-optf-mic-co-'+ box_id + ext, 'name':'opt_mic_co'});
	var div_optf_mic_hh = new Element('div.csmbol-option', {'text':' Wireless Microphone-Handheld + Audio System'});
	var sel_optf_mic_hh = new Element('select.csmbol-inp',{'id':'csmbol-optf-mic-hh-'+ box_id + ext, 'name':'opt_mic_hh'});
	
	sel_optf_mic_co.grab( new Element('option', {value:0, text:'Not Selected'}));	
	sel_optf_mic_co.grab( new Element('option', {value:1, text:'1'}));	
	//sel_optf_mic_co.grab( new Element('option', {value:2, text:'2'}));	
	var peak = true;
	var javascript_supported_date = event_date.replace(/-/g,"/"); //replace ALL '-' to '/'
	var d = new Date(javascript_supported_date);
	var dow = d.getDay();		
	if((dow>=1)&&(dow<=5)){
		switch( String(slot_flag)){
		case 'slot_am':
		case 'slot_pm':
		case 'slot_fd1':
			peak = false;
			break;
		case 'slot_fd2':
			break;
		case 'slot_cd':
			break;
		}
	}
		
	if((event_room != 'action_room')||(!peak)){
		sel_optf_mic_hh.grab( new Element('option', {value:0, text:'Not Selected'}));	
		sel_optf_mic_hh.grab( new Element('option', {value:1, text:'1'}));	
		sel_optf_mic_hh.grab( new Element('option', {value:2, text:'2'}));	
	}else{
		sel_optf_mic_hh.grab( new Element('option', {value:1, text:'1'}));	
		sel_optf_mic_hh.grab( new Element('option', {value:2, text:'2'}));				
	}
	
	div_optf_mic_co.grab(sel_optf_mic_co,'top');
	div_optf_mic_hh.grab(sel_optf_mic_hh,'top');
	
    var inp_optf_aso = null;
	//audio system only
	if((event_room != 'action_room')||(!peak)){
		var div_optf_aso = new Element('div.csmbol-option', {'text':' Audio System Only'});
		var inp_optf_aso = new Element('input',{'id':'csmbol-optf-aso-'+ box_id + ext, 'type':'checkbox', 'name':'opt_aso'});
		div_optf_aso.grab(inp_optf_aso,'top');	
	}
	

	if(inp_optf_aso){
		sel_optf_mic_co.addEvent('change', function(){if((sel_optf_mic_co.value == '0')&&(sel_optf_mic_hh.value == '0')){ inp_optf_aso.disabled = false;}else{ inp_optf_aso.disabled = true; inp_optf_aso.checked = false;}});	
		sel_optf_mic_hh.addEvent('change', function(){if((sel_optf_mic_co.value == '0')&&(sel_optf_mic_hh.value == '0')){ inp_optf_aso.disabled = false;}else{ inp_optf_aso.disabled = true; inp_optf_aso.checked = false;}});
	}
	//mic stand			
	var div_optf_ms = new Element('div.csmbol-option', {'text':' Microphone Stand'});
	var sel_optf_ms = new Element('select.csmbol-inp',{'id':'csmbol-optf-ms-'+ box_id + ext, 'name':'opt_ms'});
	
	sel_optf_ms.grab( new Element('option', {value:0, text:'Not Selected'}));	
	sel_optf_ms.grab( new Element('option', {value:1, text:'1'}));	
	sel_optf_ms.grab( new Element('option', {value:2, text:'2'}));		
	
	div_optf_ms.grab(sel_optf_ms,'top');

	//layout options
	//title
	var div_optf_title_layout = new Element('div.csmbol-option-title', {'id':'csmbol-option-title-layout-'+ box_id + ext, 'text':'Layout Options', styles:{float: 'left'}});	
	//table
	var div_optf_tbl = new Element('div.csmbol-option', {'text':' Table(120cm x 75cm)'});
	var sel_optf_tbl = new Element('select.csmbol-inp',{'id':'csmbol-optf-tbl-'+ box_id + ext, 'name':'opt_tbl'});
	
	sel_optf_tbl.grab( new Element('option', {value:0, text:'Not Selected'}));	
	sel_optf_tbl.grab( new Element('option', {value:1, text:'1'}));	
	sel_optf_tbl.grab( new Element('option', {value:2, text:'2'}));		
	sel_optf_tbl.grab( new Element('option', {value:3, text:'3'}));	
	sel_optf_tbl.grab( new Element('option', {value:4, text:'4'}));	
	sel_optf_tbl.grab( new Element('option', {value:5, text:'5'}));	
	sel_optf_tbl.grab( new Element('option', {value:6, text:'6'}));	
		
	div_optf_tbl.grab(sel_optf_tbl,'top');	
	
	//layout
	var div_optf_layout = new Element('div.csmbol-option', {'text':' Change default layout'});
	var sel_optf_layout = new Element('select.csmbol-inp',{'id':'csmbol-optf-layout-'+ box_id + ext, 'name':'opt_layout'});
	
	sel_optf_layout.grab( new Element('option', {value:'layout_thr', text:'Theatre(Default)'}));	
	sel_optf_layout.grab( new Element('option', {value:'layout_cls', text:'Classroom'}));	
	sel_optf_layout.grab( new Element('option', {value:'layout_us', text:'U-shape'}));		
	sel_optf_layout.grab( new Element('option', {value:'layout_circle', text:'Circle'}));	
		
	div_optf_layout.grab(sel_optf_layout,'top');			

	//connection options
	//title
	var div_optf_title_connection = new Element('div.csmbol-option-title', {'id':'csmbol-option-title-connection-'+ box_id + ext, 'text':'Connection Options', styles:{float: 'left'}});		
	//internet
	var div_optf_wic = new Element('div.csmbol-option', {'text':' Wireless Internet Connection'});
	var inp_optf_wic = new Element('input',{'id':'csmbol-optf-wic-'+ box_id + ext, 'type':'checkbox', 'name':'opt_wic'});
	div_optf_wic.grab(inp_optf_wic,'top');	
	//nets
	var div_optf_wnt = new Element('div.csmbol-option', {'text':' Wireless NETS Terminal'});
	var inp_optf_wnt = new Element('input',{'id':'csmbol-optf-wnt-'+ box_id + ext, 'type':'checkbox', 'name':'opt_wnt'});
	div_optf_wnt.grab(inp_optf_wnt,'top');	
	
	div_option_field.adopt(div_optf_title_visual,div_optf_pws/*,div_optf_so*/, div_optf_fcwp/*, div_optf_fcm, div_optf_wb*/,div_optf_title_audio,div_optf_mic_co,div_optf_mic_hh,div_optf_aso,div_optf_ms,div_optf_title_layout,div_optf_tbl,div_optf_layout,div_optf_title_connection,div_optf_wic,div_optf_wnt/*,div_optf_title_am,div_optf_am*/);

	return div_option_field;
}

function removeDate(box_id){
	var datetimebox_id = 'csmbol-datetimebox-'+box_id;	
	
	removeDateTimingOptioins(box_id);
	
	if(box_option_timing_container.getFirst() != null){//empty
		enableBtn(btn_sd_add_options);
		enableTab(tab_add_options);
	}
	else{ 
		disableBtn(btn_sd_add_options);
		disableTab(tab_add_options);	
		disableTab($('tab_booking_summary'));			
	}
	$(datetimebox_id).destroy();
	
	nodtb--;
	if(nodtb == 0) addFirstDateTimeBox(false, false);
};
function genBookingNumber(){
	var curTime = new Date();
	var booking_num = curTime.getTime();
	return booking_num;
};
function genBookingSlotInfo(datetimebox){

	var slot_am = datetimebox.getElement('input[name=slot_am]');			
	var slot_pm = datetimebox.getElement('input[name=slot_pm]');
	var slot_ev = datetimebox.getElement('input[name=slot_ev]');
	var slot_fc = datetimebox.getElement('select[name=slot_fc]');	
	var slot = "Empty";	
	var	slot_flag = 'slot_empty';
	var	session_slots = 1;
	if(slot_fc.get('value') != 'slot_empty'){
		switch(String(slot_fc.get('value'))){
			case 'slot_fd1':
				slot = "Full Day";	
				slot_flag = 'slot_fd1';
				session_slots = 2;
				break;				
			case 'slot_fd2':
				slot = "Full Day";	
				slot_flag = 'slot_fd2';		
				session_slots = 2;													
				break;
			case 'slot_cd':
				slot = "Complete Day";					
				slot_flag = 'slot_cd';	
				session_slots = 3;							
				break;
			default:
				break;	
		}
	}else{
		var am = false; var pm = false; var ev = false;
		if(slot_am.get('checked') == true){
			slot = "Morning Session";
			slot_flag = 'slot_am';
			session_slots = 1;
			am = true;						
		}
		if(slot_pm.get('checked') == true){
			slot = "Afternoon Session";					
			slot_flag = 'slot_pm';
			session_slots = 1;						
			pm = true;
		}
		if(slot_ev.get('checked') == true){
			slot = "Evening Session";					
			slot_flag = 'slot_ev';				
			session_slots = 1;						
			ev = true;
		}
		if(am&&(!pm)&&ev){
			slot = "Morning/Evening Session";					
			slot_flag = 'slot_ae';				
			session_slots = 1;						
		}
	};
	var booking_slot_info = {};
	booking_slot_info['slot'] = slot;	
	booking_slot_info['slot_flag'] = slot_flag;	
	booking_slot_info['session_slots'] = session_slots;	
	return booking_slot_info;
};

function genBookingInfo(changed){

	if(changed){
		var data_table = $('csmbol-booking-summary-box');//also can: $$('#csmbol-booking-summary-box');
		
		//reset summary info to empty
		data_table.empty();
		var booking_sum = $('id_booking-sum');	
		booking_sum.set('value', '0' );		
		
		var title_row = genTitleRow();
		data_table.grab(title_row);				
		
		var days = $$('.csmbol-datetimebox'); //note: $$('#id') only gets the first element instead of a group with the same id
		var total_slots = 0;
		//get date time
		days.each(function(day, index){
			var row_id = day.id.replace('csmbol-datetimebox-','');//get box_id
			var event_date = $('id_cal_'+row_id).get('value');//get the date 
			var event_room = $('sd_room_sel_'+row_id).get('value');
			var session_slots = 1; //number of slots of a session (1,2,3)
			if(event_date != ""){
				var booking_slot_info = genBookingSlotInfo(day);
				var slot = booking_slot_info['slot'];
				var slot_flag = booking_slot_info['slot_flag'];
				var session_slots = booking_slot_info['session_slots'];
				if(slot_flag != 'slot_empty'){
					if(slot_flag!='slot_ae') {
						var row = genDateTimeRow(event_date, event_room,slot,slot_flag, row_id, event_room);						
						data_table.grab(row);
						var rows_opt = genOptions(event_date,event_room, session_slots, row_id,slot_flag);		
						total_slots += session_slots;			
					}else{
						var row = genDateTimeRow(event_date, event_room,'Morning Session','slot_am', row_id);						
						data_table.grab(row);
						var rows_opt = genOptions(event_date, event_room, session_slots, row_id,'slot_am');

						var row = genDateTimeRow(event_date, event_room,'Evening Session','slot_ev', row_id+'e');						
						data_table.grab(row);
						var rows_opt = genOptions(event_date, event_room, session_slots, row_id+'e','slot_ev');
						
						total_slots += 2;
					}
				}				
			}
		});
	}
	var sum_row = genSumRow();
	data_table.grab(sum_row);
	
	var sum_text = $('data-row-booking-sum').get('text');
	var sum = parseFloat(sum_text.replace('SGD',''));
	
	var surcharge = 0;
	if(isStaff(user_group)){
		//surcharge = $('csmbol-inp-surcharge').get('value'); 
	}else{	
		if((sum/total_slots)<120){			
			surcharge = sum*rate_surcharge;
		}
	}	
	surcharge_row = genSurchargeRow(surcharge);
	sum_row.grab(surcharge_row,'before');
	var total = roundNumber((sum+surcharge), 2);
	$('id_booking-sum').set('value',total);
	$('data-row-booking-sum').set('text', 'SGD'+total);	
};

function genTitleRow(option_desc, rate, qty, type){

	var row = new Element('div.csmbol-booking-data-row', {'id':'csmbol-booking-data-row-title'});
	var item_date = new Element('div.csmbol-item-date');
	var separator = new Element('div.csmbol-item-separator');
	var item_name = new Element('div.csmbol-item-name');
	var separator1 = new Element('div.csmbol-item-separator');
	var item_rate = new Element('div.csmbol-item-rate');
	var separator2 = new Element('div.csmbol-item-separator');	
	var item_qty = new Element('div.csmbol-item-qty');
	var separator3 = new Element('div.csmbol-item-separator');
	var item_amt = new Element('div.csmbol-item-amt');	

	item_date.set('styles',{'font-size': '14px'});
	item_name.set('styles',{'font-size': '14px'});
	item_rate.set('styles',{'font-size': '14px'});
	item_qty.set('styles',{'font-size': '14px'});
	item_amt.set('styles',{'font-size': '14px'});
	
	item_date.set('text', 'Date');
	separator.set('html', '&nbsp;');					
	item_name.set('text', 'Description');
	separator1.set('html', '&nbsp;');						
	item_rate.set('text', 'Rate');	
	separator2.set('html', '&nbsp;');										
	item_qty.set('text', 'Qty');
	separator3.set('html', '&nbsp;');						
	item_amt.set('text', 'Amount' );										

	row.adopt(item_date, separator, item_name, separator1, item_rate, separator2, item_qty, separator3, item_amt);		

	return row;	
};
function genSlotRate(rate_am, rate_pm, rate_ev, slot_flag){
	switch (String(slot_flag)){
		case 'slot_am':
			rate = rate_am;	break;	
		case 'slot_pm':
			rate = rate_pm; break;
		case 'slot_ev':
			rate = rate_ev; break;
		case 'slot_fd1':
			rate = rate_am + rate_pm; break;
		case 'slot_fd2':
			rate = rate_pm + rate_ev; break;			
		case 'slot_cd':
			rate = rate_am + rate_pm + rate_ev; break;				
	};	
	
	return rate;
};
function genDateTimeRow(event_date, event_room, slot, slot_flag, slot_index){
	//getting the day of the week (dow) from event_date string
	var javascript_supported_date = event_date.replace(/-/g,"/"); //replace ALL '-' to '/'
	var d = new Date(javascript_supported_date);
	var dow = d.getDay(); //sunday is 0, reutrns 0-6

	//find the rate for the session
	var rate = rate_weekday_ev;
	switch(dow){
	case 1:	
		rate = genSlotRate(rate_mon_am[event_room], rate_mon_pm[event_room], rate_mon_ev[event_room], slot_flag);
		break;
	case 2:	
		rate = genSlotRate(rate_tue_am[event_room], rate_tue_pm[event_room], rate_tue_ev[event_room], slot_flag);
		break;
	case 3:	
		rate = genSlotRate(rate_wed_am[event_room], rate_wed_pm[event_room], rate_wed_ev[event_room], slot_flag);
		break;		
	case 4:	
		rate = genSlotRate(rate_thu_am[event_room], rate_mon_pm[event_room], rate_thu_ev[event_room], slot_flag);
		break;		
	case 5:	
		rate = genSlotRate(rate_fri_am[event_room], rate_fri_pm[event_room], rate_fri_ev[event_room], slot_flag);
		break;		
	case 6:	
		rate = genSlotRate(rate_sat_am[event_room], rate_sat_pm[event_room], rate_sat_ev[event_room], slot_flag);
		break;	
	case 0:	
		rate = genSlotRate(rate_sun_am[event_room], rate_sun_pm[event_room], rate_sun_ev[event_room], slot_flag);
		break;														
	};
	
	var row = new Element('div.csmbol-booking-data-row-booking-entry', {'id':'csmbol-booking-data-row-booking-entry-'+slot_index});
	var item_date = new Element('div.csmbol-item-date');
	var separator = new Element('div.csmbol-item-separator');
	var item_name = new Element('div.csmbol-item-name');
	var separator1 = new Element('div.csmbol-item-separator');
	var item_rate = new Element('div.csmbol-item-rate');
	var separator2 = new Element('div.csmbol-item-separator');	
	var item_qty = new Element('div.csmbol-item-qty');
	var separator3 = new Element('div.csmbol-item-separator');
	var item_amt = new Element('div.csmbol-item-amt');
	//record slot indicator
	var item_slot_flag = new Element('input',{'type':'hidden', 'id':'csmbol-item-slot-flag', 'value':slot_flag});	
	var item_room = new Element('input',{'type':'hidden', 'id':'csmbol-item-room-title', 'value':event_room});	

	item_date.set('styles',{'font-weight':'bold','font-size': '12.5px'});
	item_name.set('styles',{'font-size': '12px'});
	item_rate.set('styles',{'font-size': '12.5px'});
	item_qty.set('styles',{'font-size': '12.5px'});
	item_amt.set('styles',{'font-size': '12.5px'});
			
	item_date.set('text', event_date);
	separator.set('html', '&nbsp;');					
	item_name.set('text', getRoomTitle(event_room)+' - '+slot);
	separator1.set('html', '&nbsp;');	

	var inp_rate = new Element('input.csmbol-inp', {id:'csmbol-inp-rate',value:roundNumber(rate,2),styles:{width: '45px'}});
	item_rate.grab(inp_rate);
	if(isStaff(user_group)){
		inp_rate.disabled = false;		
		inp_rate.readOnly = false;
	}else{						
		inp_rate.disabled = true;
		inp_rate.readOnly = true;
	}	
	separator2.set('html', '&nbsp;');
	var inp_qty = new Element('input.csmbol-inp', {id:'csmbol-inp-qty',value:1,styles:{width: '16px'}});
	item_qty.grab(inp_qty);										
	if(isStaff(user_group)){
		inp_qty.disabled = true;
		inp_qty.readOnly = true;
	}else{
		inp_qty.disabled = true;
		inp_qty.readOnly = true;
	}	
	separator3.set('html', '&nbsp;');						
	item_amt.set('text', 'SGD'+ roundNumber((rate * inp_qty.get('value')),2) );										
		
	row.adopt(item_date, separator, item_name, separator1, item_rate, separator2, item_qty, separator3, item_amt, item_slot_flag, item_room);		
	
	var booking_sum = $('id_booking-sum');	
	booking_sum.set('value', parseFloat(booking_sum.get('value')) + parseFloat(rate * inp_qty.get('value')) );
	
	return row;	
};

function genOptionRow(option_desc, rate, qty, type, slot_index){

	var row = new Element('div.csmbol-booking-data-row',{'id':'booking-option-row-'+slot_index});
	var item_date = new Element('div.csmbol-item-date');
	var separator = new Element('div.csmbol-item-separator');
	var item_name = new Element('div.csmbol-item-name');
	var separator1 = new Element('div.csmbol-item-separator');
	var item_rate = new Element('div.csmbol-item-rate');
	var separator2 = new Element('div.csmbol-item-separator');	
	var item_qty = new Element('div.csmbol-item-qty');
	var separator3 = new Element('div.csmbol-item-separator');
	var item_amt = new Element('div.csmbol-item-amt');	
	var opt_desc = new Element('input',{'type':'hidden','name':'opt_desc'});

	item_date.set('styles',{'font-size': '11.5px'});
	item_name.set('styles',{'font-size': '11.5px'});
	item_rate.set('styles',{'font-size': '11.5px'});
	item_qty.set('styles',{'font-size': '11.5px'});
	item_amt.set('styles',{'font-size': '11.5px'});
		
	item_date.set('html', '&nbsp;');
	separator.set('html', '&nbsp;');					
	item_name.set('text', option_desc);
	separator1.set('html', '&nbsp;');
	var inp_rate = new Element('input.csmbol-inp', {id:'csmbol-inp-rate',value:rate,styles:{width: '45px'}});
	item_rate.grab(inp_rate);
	if(isStaff(user_group)){
		inp_rate.disabled = false;		
		inp_rate.readOnly = false;
	}else{						
		inp_rate.disabled = true;
		inp_rate.readOnly = true;
	}
	separator2.set('html', '&nbsp;');
	var inp_qty = new Element('input.csmbol-inp', {id:'csmbol-inp-qty',value:qty,styles:{width: '16px'}});
	item_qty.grab(inp_qty);										
	if(isStaff(user_group)){
		inp_qty.disabled = false;
		inp_qty.readOnly = false;
	}else{
		inp_qty.disabled = true;
		inp_qty.readOnly = true;
	}	
	separator3.set('html', '&nbsp;');						
	item_amt.set('text', 'SGD'+ (rate * qty) );				
	opt_desc.set('value', option_desc);						
	
	row.adopt(item_date, separator, item_name, separator1, item_rate, separator2, item_qty, separator3, item_amt, opt_desc);
//	var entry_id = 'csmbol-booking-data-row-booking-entry-'+slot_index; 
	$('entry-option-container-'+slot_index).grab(row);		

	var booking_sum = $('id_booking-sum');	
	booking_sum.set('value', parseFloat(booking_sum.get('value')) + parseFloat(rate * qty) );
	
	return row;	
};

function genOptions(event_date, event_room, session_slots, slot_index,slot_flag){
	var option_container = new Element('div.csmbol-option-container',{'id':'entry-option-container-'+slot_index});
	$('csmbol-booking-summary-box').grab(option_container);
	//get options
	var booking_options = $$('#csmbol-option-box');

	var opt_es = $('csmbol-optf-es-'+slot_index);
	var opt_ec = $('csmbol-optf-ec-'+slot_index);	
	var opt_pws = $('csmbol-optf-pws-'+slot_index);

//	var opt_so = $('csmbol-optf-so-'+slot_index);
	var sel_optf_fcwp = $('csmbol-optf-fcwp-'+slot_index);
//	var opt_fcm = $('csmbol-optf-fcm-'+slot_index);
//	var opt_wb = $('csmbol-optf-wb-'+slot_index);
	var opt_mic_co = $('csmbol-optf-mic-co-'+slot_index);
	var opt_mic_hh = $('csmbol-optf-mic-hh-'+slot_index);
	var opt_aso = $('csmbol-optf-aso-'+slot_index);
	var opt_ms = $('csmbol-optf-ms-'+slot_index);
	var opt_wic = $('csmbol-optf-wic-'+slot_index);					
	var opt_wnt = $('csmbol-optf-wnt-'+slot_index);
	var opt_tbl = $('csmbol-optf-tbl-'+slot_index);
	var opt_layout = $('csmbol-optf-layout-'+slot_index);

	var	index = 0;
	var rows = new Array();
	var	opt_desc = '';
	var	rate = 0;
	var	qty = 0;

	//timing options
	var select_start = $('csmbol-select-start-'+slot_index);		
	var select_end = $('csmbol-select-end-'+slot_index);		
	if(select_start.get('value') != '0'){
		opt_desc = 'Early Setup Option';
		rate = rate_opt_15min;
		qty = select_start.get('value');
		if(isStaff(user_group)) qty = 0;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select', slot_index);		
		index += 1;
	}
	//title option
	var event_title = $('csmbol-option-eventtitle-'+slot_index).get('value');
	if ((event_title == '')||(event_title == title_indicator)) event_title = 'event';
	event_title = event_title.replace(/\"/g,'\\"'); //replace ALL " to \" in a string so that later the json_decode can handle data with " inside it
//	window.alert(event_title);	
	event_title = encodeURIComponent(event_title);//encode all special chars
//	window.alert(event_title);
	//get event title and store it in hidden input
	var event_title_input = new Element('input',{'type':'hidden', 'name':'event-title-input', 'id':'event-title-input-'+slot_index, 'value':event_title});	
	$('csmbol-booking-data-row-booking-entry-'+slot_index).grab(event_title_input);	
	//also insert time to date time row
	desc = $('csmbol-booking-data-row-booking-entry-'+slot_index).getElement('div[class=csmbol-item-name]');
	var text = desc.get('text');
	var starttime = select_start.getSelected()[0].get('text');
	text += ' ('+starttime;
	desc.set('text',text);
	var start_time_input = new Element('input',{'type':'hidden', 'name':'start-time-input', 'id':'start-time-input-'+slot_index, 'value':starttime});	
	$('csmbol-booking-data-row-booking-entry-'+slot_index).grab(start_time_input);	

	if(select_end.get('value') != '0'){
		opt_desc = 'Extended Clear-up Option';
		rate = rate_opt_15min;
		qty = select_end.get('value');
		if(isStaff(user_group)) qty = 0;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}		
	desc = $('csmbol-booking-data-row-booking-entry-'+slot_index).getElement('div[class=csmbol-item-name]');
	var text = desc.get('text');
	var endtime = select_end.getSelected()[0].get('text');				
	text += '-'+endtime+')';
	desc.set('text',text);	
	var end_time_input = new Element('input',{'type':'hidden', 'name':'end-time-input', 'id':'end-time-input-'+slot_index, 'value':endtime});		
	$('csmbol-booking-data-row-booking-entry-'+slot_index).grab(end_time_input);		
	//	visual options
	if(opt_pws.get('checked') == false){
		opt_desc = 'No Projector';
		rate = rate_opt_pws;
		qty = -1*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}/*else if(opt_so.get('checked') == true){
		opt_desc = 'Screen Only';
		rate = rate_opt_so;
		qty = 1*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;		
	}*/
	if(sel_optf_fcwp.get('value') != '0'){
		opt_desc = ' Flip Chart (with 25pcs paper)';
		rate = rate_opt_fcwp;
		qty = sel_optf_fcwp.get('value')*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}
/*	if(opt_fcm.get('checked') == true){
		opt_desc = 'Flip Chart Marker Set';
		rate = rate_opt_fcm;
		qty = 1*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}*/
/*	if(opt_wb.get('checked') == true){
		opt_desc = 'White-board with white-board marker';
		rate = rate_opt_wb;
		qty = 1*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}*/		
	//audio options
	if(opt_mic_co.get('value') != '0'){
		opt_desc = 'Wireless Microphone-Clip on + Audio System';
		rate = rate_opt_mic_co;
		qty = opt_mic_co.get('value')*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}
	
	var peak = true;
	var javascript_supported_date = event_date.replace(/-/g,"/"); //replace ALL '-' to '/'
	var d = new Date(javascript_supported_date);
	var dow = d.getDay();		
	if((dow>=1)&&(dow<=5)){
		switch( String(slot_flag)){
		case 'slot_am':
		case 'slot_pm':
		case 'slot_fd1':
			peak = false;
			break;
		case 'slot_fd2':
			break;
		case 'slot_cd':
			break;
		}
	}	
	
	def_mic_hh = 0;
	def_mic_hh_msg = 'Wireless Microphone-Handheld + Audio System ';
	if((event_room == 'action_room')&&peak){
		def_mic_hh = 1;
		def_mic_hh_msg = 'Additional Microphone-Handheld';
	}
	if(opt_mic_hh.get('value') != def_mic_hh){
		opt_desc = def_mic_hh_msg;
		rate = rate_opt_mic_hh;
		qty = (opt_mic_hh.get('value') - def_mic_hh)*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}
	if(opt_aso){
		if(opt_aso.get('checked') == true){
			opt_desc = 'Audio System Only';
			rate = rate_opt_aso;
			if(opt_pws.get('checked') == true){
				rate = 0;	
			}
			qty = 1*session_slots;
			rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
			index += 1;
		}		
	}
	if(opt_ms.get('value') != '0'){
		opt_desc = 'Microphone Stand';
		rate = rate_opt_ms;
		qty = opt_ms.get('value')*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}
	//connection options
	if(opt_wic.get('checked') == true){
		opt_desc = 'Wireless Internet Connection ';
		rate = rate_opt_wic;
		qty = 1*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}	
	if(opt_wnt.get('checked') == true){
		opt_desc = 'Wireless NETS Terminal ';
		rate = rate_opt_wnt;
		qty = 1*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}	
	
	//layout options
	if(opt_tbl.get('value') != '0'){
		opt_desc = 'Table (120cm x 75cm)';
		rate = rate_opt_tbl;
		//BL: Tables are free for weekday day sessions;

		if((dow>=1)&&(dow<=5)){
			switch( String(slot_flag)){
			case 'slot_am':
			case 'slot_pm':
			case 'slot_fd1':
				rate = 0;
				break;
			case 'slot_fd2':
				rate = 0;//rate_opt_tbl * 0.5;
				break;
			case 'slot_cd':
				rate = 	0;//rate_opt_tbl * 0.3;
				break;
			}
		}
		qty = opt_tbl.get('value')*session_slots;
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}
	if(opt_layout.get('value') != 'layout_thr'){
		opt_desc = 'Change defualt layout to';
		var layout = opt_layout.get('value');
		switch ( String(layout) )
		{
			case "layout_cls":
				opt_desc += ' Classroom';
				break;
			case "layout_us":
				opt_desc += ' U-shape';
				break;
			case "layout_circle":
				opt_desc += ' Circle';
				break;
			default:
				opt_desc += ' Theatre';
				break;								
		};
		rate = rate_opt_layout;
		//BL: Tables are free for weekday day sessions;
		if((dow>=1)&&(dow<=5)){
			switch( String(slot_flag)){
			case 'slot_am':
			case 'slot_pm':
			case 'slot_fd1':
				rate = 0;
				break;
			case 'slot_fd2':
				rate = 0;//rate_opt_tbl * 0.5;
				break;
			case 'slot_cd':
				rate = 	0;//rate_opt_tbl * 0.3;
				break;
			}
		}		
		qty = 1; //layout change is one-time
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}
	//PH info
	var ph_info = $('csmbol-option-ph-'+slot_index);
	if(ph_info){ 
		var opt_desc = 'Public Holiday Surcharge';
		rate = rate_opt_ph;
		qty = 1; //layout change is one-time
		if(session_slots >1) rate *= 2; //BL: Public Holiday Surcharge
		rows[index] = genOptionRow(opt_desc, rate, qty, 'select',slot_index);		
		index += 1;
	}
									
	return rows;
};

function genSumRow(){

	var row = new Element('div.csmbol-booking-data-row');
	var item_date = new Element('div.csmbol-item-date');
	var separator = new Element('div.csmbol-item-separator');
	var item_name = new Element('div.csmbol-item-name');
	var separator1 = new Element('div.csmbol-item-separator');
	var item_rate = new Element('div.csmbol-item-rate');
	var separator2 = new Element('div.csmbol-item-separator');	
	var item_qty = new Element('div.csmbol-item-qty');
	var separator3 = new Element('div.csmbol-item-separator');
	var item_amt = new Element('div.csmbol-item-amt',{'id':'data-row-booking-sum'});	
	
	var booking_sum = $('id_booking-sum');	
		
	item_date.set('html', '&nbsp;');
	separator.set('html', '&nbsp;');					
	item_name.set('html', '&nbsp;');
	separator1.set('html', '&nbsp;');						
	item_rate.set('text', 'Total:');	
	separator2.set('html', '&nbsp;');										
	if(isStaff(user_group)){
		var btn_r = new Element('a',{text:'R', id:'csmbol-btn-r',styles:{cursor: 'pointer'}});
		item_qty.grab(btn_r);
		btn_r.addEvent('click', function(event){
			event.stop();
			var total = 0;
			datetime_rows = $$('.csmbol-booking-data-row-booking-entry');
			var valid_val = true;
			var row_total = collectAmt(datetime_rows);
			if(row_total != -1){
				total += row_total;
				
				option_containers = $$('.csmbol-option-container');
				option_containers.each(function(container, index){
					var option_rows = container.getChildren('div[class=csmbol-booking-data-row]');
					var row_total = collectAmt(option_rows);

					if(row_total != -1)
						total += row_total;
					else{ 
						valid_val = false;
						window.alert('Invalid input!');	
					}
				});	
			}else{
				valid_val = false;				
				window.alert('Invalid input!');	
			}	
			
			var surcharge = $('csmbol-inp-surcharge').get('value'); //total * rate_surcharge;			
			if(!isNumber(surcharge)){ 
				valid_val = false;
				window.alert('Invalid input!');
			}
			
			if(valid_val){			
				var subtotal = roundNumber((parseFloat(total)+parseFloat(surcharge)), 2);
				$('data-row-surcharge').set('text','SGD'+roundNumber(surcharge,2));
				item_amt.set('text', 'SGD'+subtotal);
				$('id_booking-sum').set('value', subtotal);									
			}
		});		
	}else{	
		item_qty.set('html', '&nbsp;');
	}
	separator3.set('html', '&nbsp;');						
	item_amt.set('text', 'SGD'+roundNumber(booking_sum.get('value'), 2));										
	item_rate.set('styles',{'font-weight': 'bold', 'font-size': '12px'});
			
	row.adopt(item_date, separator, item_name, separator1, item_rate, separator2, item_qty, separator3, item_amt);		
	return row;	
};
function genSurchargeRow(surcharge){

	var row = new Element('div.csmbol-booking-data-row');
	var item_date = new Element('div.csmbol-item-date');
	var separator = new Element('div.csmbol-item-separator');
	var item_name = new Element('div.csmbol-item-name');
	var separator1 = new Element('div.csmbol-item-separator');
	var item_rate = new Element('div.csmbol-item-rate');
	var separator2 = new Element('div.csmbol-item-separator');	
	var item_qty = new Element('div.csmbol-item-qty');
	var separator3 = new Element('div.csmbol-item-separator');
	var item_amt = new Element('div.csmbol-item-amt',{'id':'data-row-surcharge'});	
	
	item_date.set('html', '&nbsp;');
	separator.set('html', '&nbsp;');					
	item_name.set('html', 'Surcharge:');
	separator1.set('html', '&nbsp;');
	var inp_rate = new Element('input.csmbol-inp', {id:'csmbol-inp-surcharge',value:roundNumber(surcharge, 2),styles:{width: '45px'}});
	item_rate.grab(inp_rate);
	if(isStaff(user_group)){
		inp_rate.disabled = false;		
		inp_rate.readOnly = false;
	}else{						
		inp_rate.disabled = true;
		inp_rate.readOnly = true;
	}
	separator2.set('html', '&nbsp;');										
	item_qty.set('html', '&nbsp;');
	separator3.set('html', '&nbsp;');						
	item_amt.set('text', 'SGD'+roundNumber(surcharge, 2));										
	item_rate.set('styles',{'font-size': '12px'});
	row.adopt(item_date, separator, item_name, separator1, item_rate, separator2, item_qty, separator3, item_amt);		

	return row;	
};

function collectAmt(rows){
	var rows_total = 0;
	rows.some(function(row, index2){
		var rate_div = row.getElement('div[class=csmbol-item-rate]');
		var qty_div = row.getElement('div[class=csmbol-item-qty]');
		var rate_inp = rate_div.getChildren('input[id=csmbol-inp-rate]');
		var qty_inp = qty_div.getChildren('input[id=csmbol-inp-qty]');
		var rate_val = rate_inp.get('value');
		var qty_val = qty_inp.get('value');	
		if(isNumber(rate_val)&&(isNumber(qty_val))){
			var amt_new = parseFloat(rate_val * qty_val);
			var amt_div = row.getElement('div[class=csmbol-item-amt]');
			amt_div.set('text', 'SGD'+parseFloat(amt_new));
			rows_total += amt_new;
		}else{
			rows_total = -1;
			return rows_total;
		}
	});	
	return rows_total;
}

function roundNumber(num, dec) {
  var result = String(Math.round(num*Math.pow(10,dec))/Math.pow(10,dec));
  if(result.indexOf('.')<0) {result+= '.';}
  while(result.length- result.indexOf('.')<=dec) {result+= '0';}
  return result;
};

function showAvailability(box_number){
	var selected_date = $('id_cal_'+box_number).get('value');
	var selected_room = $('sd_room_sel_'+box_number).get('value');
		
	var lip = $('lip_'+box_number);
	if(!lip) lip = new Element('input',{'id':'lip_'+box_number,'type':'hidden', 'value':0});
	$('csmbol-datetimebox-'+box_number).grab(lip);//IE: 'input' can't grab elements
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=updateTimeBox&format=raw',
		onRequest: function(){
			$('sd_room_sel_'+box_number).disabled = true;
			disableBtn(btn_sd_add_options);
			disableTab(tab_add_options);
			disableTab($('tab_booking_summary'));
			var loading_box_id = 'csmbol-timebox-loading-'+box_number;
			var loading_box = $(loading_box_id);
			if(loading_box) loading_box.destroy();
			loading_box = new Element( 'div.csmbol-timebox', {'id': loading_box_id});
			var loading_text = new Element('div.loading-text', {'text': 'Checking slot availability...'});	
			loading_box.addClass('ajax-loading');
			loading_box.grab(loading_text);			
			$('csmbol_date_'+box_number).grab(loading_box,'after');
			$('lip_'+box_number).value++;
		},
		onComplete: function(response){
			var container_box_id = 'box_datetimebox_container';
			if(response.rts =='error'){
				disableFunctions();				
				$(container_box_id).set('html', response.rtmsg+response.rtmsg_embeded_code)
				 return;
			}			
			$('sd_room_sel_'+box_number).disabled = false;
						
			var timebox_loading = $('csmbol-timebox-loading-'+box_number);
			var timebox_old = $('csmbol-timebox-'+box_number);
			var timebox = timebox_loading;
			if(timebox_old) {timebox_old.empty();timebox = timebox_old}			
			var lip = $('lip_'+box_number);
			lip.value--;						
			if(lip.value==0){
				if(timebox_loading) timebox_loading.empty().removeClass('ajax-loading');	
				var resp_html = response.htmlcode;
	//				var dow = response.dow;
				var slot_am = response.slot_am;	
				var slot_pm = response.slot_pm;	
				var slot_ev = response.slot_ev;	
				var slot_fd1 = response.slot_fd1;
				var slot_fd2 = response.slot_fd2;	
				var slot_cd = response.slot_cd;		
				var ph = response.ph;//public holiday
				$('inp_ph_'+box_number).set('value',ph);
														
				var timebox_id = 'csmbol-timebox-'+box_number;	
						
				timebox.set('html', resp_html);  
				timebox.id = timebox_id;//recover timebox id
	
				var fc_select = $('slot_fc_'+box_number);
				fc_select.disabled = true;	
				if((slot_fd1 == 'booked')||(slot_fd2 == 'booked')||(slot_cd == 'booked')||(((slot_am=='booked')||(slot_am=='client_pending'))&&((slot_ev=='booked')||(slot_ev=='client_pending')))||((slot_pm=='booked')||(slot_pm=='client_pending')))
					fc_select.getParent().addClass('csmbol-bs-booked');
				else if ((slot_fd1 == 'client_pending')||(slot_fd2 == 'client_pending')||(slot_cd == 'client_pending')||(((slot_am=='booked')||(slot_am=='client_pending'))&&((slot_ev=='booked')||(slot_ev=='client_pending'))))
					fc_select.getParent().addClass('csmbol-bs-cp');  
						else fc_select.disabled = false;
						
				if(!isStaff(user_group)){	//if staff, don't destroy the full-day session dropdown list items	
					//handles fd2 select-option-only, when slot_am is booked or pending
					if(((slot_am=='booked')||(slot_am=='client_pending'))&&(slot_pm=='avail')&&(slot_ev=='avail')){
						fc_select.getElement('option[value=slot_cd]').destroy();//setStyle('display','none'); IE/Safari ns
						fc_select.getElement('option[value=slot_fd1]').destroy();//setStyle('display','none');			
					}
					//handles fd1 select-option-only, when slot_ev is booked or pending
					if(((slot_ev=='booked')||(slot_ev=='client_pending'))&&(slot_am=='avail')&&(slot_pm=='avail')){
						fc_select.getElement('option[value=slot_cd]').destroy();//setStyle('display','none'); 
						fc_select.getElement('option[value=slot_fd2]').destroy();//setStyle('display','none');			
					}				
				}
				//display slot availability	
				var am_checkbox = $('slot_am_'+box_number);
				
				if(isStaff(user_group)){//always allow staff to select
					am_checkbox.disabled = false;	
				}else{
					am_checkbox.disabled = true;	
				}
				if(slot_am == 'booked')
					am_checkbox.getParent().addClass('csmbol-bs-booked');
				else if (slot_am == 'client_pending')
					am_checkbox.getParent().addClass('csmbol-bs-cp');  
						else {am_checkbox.disabled = false;am_checkbox.getParent().addClass('csmbol-bs-avail');}
				var pm_checkbox = $('slot_pm_'+box_number);
				if(isStaff(user_group)){//always allow staff to select
					pm_checkbox.disabled = false;	
				}else{
					pm_checkbox.disabled = true;	
				}	
				if(slot_pm == 'booked')
					pm_checkbox.getParent().addClass('csmbol-bs-booked');
				else if (slot_pm == 'client_pending')
					pm_checkbox.getParent().addClass('csmbol-bs-cp');  
						else {pm_checkbox.disabled = false;pm_checkbox.getParent().addClass('csmbol-bs-avail');}
				var ev_checkbox = $('slot_ev_'+box_number);
				if(isStaff(user_group)){//always allow staff to select
					ev_checkbox.disabled = false;	
				}else{
					ev_checkbox.disabled = true;	
				}	
				if(slot_ev == 'booked')
					ev_checkbox.getParent().addClass('csmbol-bs-booked');
				else if (slot_ev == 'client_pending')
					ev_checkbox.getParent().addClass('csmbol-bs-cp');  
						else {ev_checkbox.disabled = false;	ev_checkbox.getParent().addClass('csmbol-bs-avail');}	
				updateTimingTitleOption('slot_am_'+box_number);	
			}
		}
	}).send('current_room='+selected_room+'&box_number='+box_number+'&date='+selected_date);
};
function genBookingEntriesInfo(user){
	var booking_entries = $$('.csmbol-booking-data-row-booking-entry');//using id as selector only gets the first element
	var booking_entries_info = [];
	booking_entries.each(function(entry, index){

		var item_date = entry.getElement('div[class=csmbol-item-date]');//getChildren('.csmbol-item-date')[0];
		var item_slot_flag = entry.getChildren('#csmbol-item-slot-flag')[0];
		var item_event_room = entry.getChildren('#csmbol-item-room-title')[0];
		var date = item_date.get('text');
		var slot_flag = item_slot_flag.get('value');
		var event_room = item_event_room.get('value');		

		var booking_status = 'pending';
		switch (String(user)){
			case 'admin':
			booking_status = 'admin_pending';
			break;
			case 'client':
			booking_status = 'client_pending';			
			break;
			default:
			booking_status = 'pending';				
			break;
		};
		var seq = 'seq'+index;			
		
		var start_time_hm = entry.getElement('input[name=start-time-input]').get('value');
		var end_time_hm = entry.getElement('input[name=end-time-input]').get('value');		
		//and this is an object
		var entry_info = {};
		
		entry_info.seq = seq; //this syntax also works: entry_info['seq'] = seq;
		entry_info.date = date;
		entry_info.event_room = event_room;
		entry_info.title = start_time_hm.replace(':','') +'-'+ end_time_hm.replace(':','') + ' ' + entry.getElement('input[name=event-title-input]').get('value');
//		window.alert(entry_info.title);
		entry_info.starttime = start_time_hm;//+':00';//$('start-time-input-'+index).get('value');	//getting from hidden input
		entry_info.endtime = end_time_hm;//+':00';//$('end-time-input-'+index).get('value');
		entry_info.slot_flag = slot_flag;
		entry_info.booking_status = booking_status;
		
		//get options
		var entry_id = entry.get('id');
		var option_container_id = entry_id.replace('csmbol-booking-data-row-booking-entry','entry-option-container');
		entry_options = $(option_container_id).getChildren('div[class=csmbol-booking-data-row]');
		option_entries = [];
		option_number = [];
		entry_options.each(function(entry_option, index2){
			option_entries[index2] = entry_option.getElement('input[name=opt_desc]').get('value');
			var qty_div = entry_option.getElement('div[class=csmbol-item-qty]');	
			var qty_inp = qty_div.getChildren('input[id=csmbol-inp-qty]');		
			option_number[index2] = String(qty_inp.get('value'));
		});
		entry_info.entry_options = option_entries;
		entry_info.entry_options_number = option_number;
		 							
		booking_entries_info[index] = entry_info;
	});
	booking_entries_info[booking_entries_info.length] = $('data-row-booking-sum').get('text');//sum amt
	booking_entries_info[booking_entries_info.length] = document.getElement('input[name=item_number]').get('value')//booking number;	

	addmsg = $('opt_addmsg').get('value');
	addmsg = addmsg.replace(/\"/g,'\\"'); //replace ALL " to \" in a string so that later the json_decode can handle data with " inside it
	booking_entries_info[booking_entries_info.length] = encodeURIComponent(addmsg);//addtional message

	booking_entries_info[booking_entries_info.length] = $('client_phone').get('value');//phone number
	
	return booking_entries_info;
};

function genStartEndTime(slot_flag, early_step, extend_step){
	var starttime = 'emp';
	var endtime = 'emp';
	var minute_display_start = 'emp';
	var minute_display_end = 'emp';	
	var hour_start = 0;
	var hour_end = 0;
	var minute_start = 0;
	var minute_end = 0;
	var hour_early_offset = 0;
	var hour_extend_offset = 0;
	
	switch (String(slot_flag)){
		case 'slot_am':
		hour_start = hour_start_am;
		hour_end = hour_end_am;
		minute_start = minute_start_am;
		minute_end = minute_end_am;
		break;
		case 'slot_pm':
		hour_start = hour_start_pm;
		hour_end = hour_end_pm;
		minute_start = minute_start_pm;
		minute_end = minute_end_pm;
		break;
		case 'slot_ev':
		hour_start = hour_start_ev;
		hour_end = hour_end_ev;
		minute_start = minute_start_ev;
		minute_end = minute_end_ev;
		break;
		case 'slot_fd1':
		hour_start = hour_start_am;
		hour_end = hour_end_pm;
		minute_start = minute_start_am;
		minute_end = minute_end_pm;
		break;
		case 'slot_fd2':
		hour_start = hour_start_pm;
		hour_end = hour_end_ev;
		minute_start = minute_start_pm;
		minute_end = minute_end_ev;
		break;			
		case 'slot_cd':
		hour_start = hour_start_am;
		hour_end = hour_end_ev;
		minute_start = minute_start_am;
		minute_end = minute_end_ev;
		break;
		default:
		window.alert('start time end time error');
		break;
	}
	
	minute_start =30; //30min setup
	hour_start -= 1;
	minute_end = 30; //30min clear up
	
	var early_minute = minute_start - 15*early_step; 
	if (early_minute != 0) minute_display_start = early_minute; else minute_display_start = '00';
	if (early_minute < 0) {hour_early_offset = Math.floor(early_minute/60); minute_display_start -= hour_early_offset*60;if(minute_display_start==0) minute_display_start = '00';}//hour_early_offset (-1,0)
	var dd_hour_start = parseInt(hour_start + hour_early_offset);
	if (dd_hour_start <10) dd_hour_start = '0'+ dd_hour_start;
	starttime = dd_hour_start + ':' + minute_display_start;	
	
	var extend_minute = minute_end + 15*extend_step;
	if ((extend_minute != 60)&&(extend_minute != 0)) minute_display_end = extend_minute; else minute_display_end = '00';
	if (extend_minute >= 60) {hour_extend_offset = Math.floor(extend_minute/60); if(extend_minute > 60) minute_display_end -= hour_extend_offset*60; if(minute_display_end==0) minute_display_end = '00';}//hour_early_offset (0,1)
	var dd_hour_end = parseInt(hour_end + hour_extend_offset);
	if (dd_hour_end <10) dd_hour_end = '0'+ dd_hour_end;
	endtime = dd_hour_end + ':' + minute_display_end;

	var startendtime = {};
	startendtime['starttime'] = starttime;
	startendtime['endtime'] = endtime;
	return startendtime;
};

function processEntriesBatch(process, action_name, user, entries_info){
	var booking_entries_info = new Array();
	if(!entries_info)
		booking_entries_info = genBookingEntriesInfo(user);	
	else
		booking_entries_info = entries_info;
	
	var json_data = null;
	if(process != 'makeBooking'){
		json_data = JSON.encode(booking_entries_info);
		//window.alert(json_data);
	}
		
	var action = 'processed';
	if(action_name)
		action = action_name;	
			
	var noe = booking_entries_info.length - noae;
//	window.alert(noe);
	
	client_info = "";
	if(user == 'admin'){
		client_name = $('client_name').get('value');
		client_email = $('client_email').get('value');
		client_phone = $('client_phone').get('value');		
		client_company = $('client_company').get('value');				
		client_info = "&client_name="+encodeURIComponent(client_name)+"&client_email="+client_email+"&client_phone="+client_phone+"&client_company="+encodeURIComponent(client_company);	
	}else{
		if(process != 'makeBooking'){
			client_phone = $('client_phone').get('value');
			client_info = "&client_name="+""+"&client_email="+""+"&client_phone="+client_phone+"&client_company="+"";			
		}
	};
	
	var container_box_id = 'csmbol-booking-box';
	if((process == 'makeBooking')/*&&(user=='client')*/) 
		container_box_id = 'csmbol-booking-completed-box';

	new Request.JSON({

		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task='+process+'&format=raw',
		onRequest: function(){
			
			var loading_text = 'Preparing your bookings...'
			if((process == 'makeBooking')/*&&(user=='client')*/){
//				gotoCompletedPage();
				disableBtn(btn_bc_new_booking);
				loading_text = 'Confirming your bookings...';
			}
			if(process == 'readyEntriesForBooking'){
				disableBtn(btn_bn_restart_booking);
			}
//			window.alert(noe);
			for(index=0; index<noe; index++){//no for..in interation in multi-dimentional array in javascript
				var entry_info = booking_entries_info[index];
				var seq = entry_info['seq'];	
				
				var loading_box = new Element( 'div.csmbol-booking-entry', {'id': 'csmbol-booking-entry-loading'});
				var loading_seq_id = new Element('input',{'type':'hidden', 'id':'csmbol-item-loading-seq'+index, 'value':seq});
				var loading_text_div = new Element('div.loading-text', {'text': loading_text});	
				loading_box.grab(loading_text_div);		
				$(container_box_id).grab(loading_box);
				loading_box.addClass('ajax-loading');	
				loading_box.grab(loading_seq_id);		
//				window.alert(noe);			
			};				
		},

		onComplete: function(response){
			if(response.rts =='error'){
				$(container_box_id).set('html', response.rtmsg+response.rtmsg_embeded_code)
				 return;
			}
			if(process == 'makeBooking'){
				//makeBooking() in the controller will send back the booking entries info 				
				var noe = response.length - noae;
				booking_entries_info = response;
				for ( i=0; i<noe; i++){
					var entry_info = {};
					entry_info.seq = response[i]['seq'];
					entry_info.date = response[i]['date'];
					entry_info.event_room = response[i]['event_room'];
					entry_info.title = response[i]['title'];
					entry_info.starttime = response[i]['starttime'];	
					entry_info.endtime = response[i]['endtime'];
					entry_info.slot_flag = response[i]['slot_flag'];
					entry_info.booking_status = 'client_confirmed';
					booking_entries_info[i] = entry_info;										
				}
/*				booking_entries_info[noe] = response[noe];//amt
				booking_entries_info[noe+1] = response[noe+1];//booking number
				booking_entries_info[noe+2] = response[noe+2];//additional message
*/			};			
			
			var loading_boxes = $(container_box_id).getChildren();
			
			loading_boxes.each(function(loading_box, index){
				if(loading_box.id != 'tnc-box'){

					if($('tnc-box')) entry_id = index -1;/*-1 because of the tnc box is box 0*/ else entry_id = index; //not -1 if no tnc box
					if(process == 'makeBooking') entry_id = index; //no more tnc box when makebooking
					loading_box.removeClass('ajax-loading');
					loading_box.empty();
					loading_box.id = 'csmbol-booking-result';//recover timebox id
					if(process == 'makeBooking'){					
						var message = 'Session: '+booking_entries_info[entry_id]['date']+' | '+booking_entries_info[entry_id]['starttime']+' to '+booking_entries_info[entry_id]['endtime']+' is '+action_name+'.'					
						loading_box.addClass('csmbol-msg-success');		
						loading_box.set('html', message);		
					}else if(process == 'readyEntriesForBooking'){
						enableBtn(btn_bn_restart_booking);
						var session_info = 'Session: '+booking_entries_info[entry_id]['date']+' | '+booking_entries_info[entry_id]['starttime']+' to '+booking_entries_info[entry_id]['endtime'];
						switch(String(response.session_result[entry_id])){
							case 'block_success':
							var pending_sec = response.pending_sec;//pending seconds
							loading_box.addClass('csmbol-msg-ready');		
							var message1 = session_info+'&nbsp;is bloacked for&nbsp;';
							var countdown_text_div = new Element('div', {'html': message1, styles:{float:'left'}});					
							var countdown_div = new Element('div', {'id': 'countdown-'+index, styles:{float:'left'}});	
							var countdown_text_div2 = new Element('div', {'html': '&nbsp;minutes for your booking.', styles:{float:'left'}});	
							loading_box.adopt(countdown_text_div,countdown_div,countdown_text_div2);							
							var start = pending_sec;
							var fireevent = false; if(entry_id==0) fireevent= true;//only the first entry box fires countdown event
							countdown(start,countdown_div.id,fireevent );
							break;
							case 'client_pending':
							action_name = 'pending by another user, please check again in 15 minutes';
							loading_box.addClass('csmbol-msg-error');
							var message = session_info+' is '+action_name+'.'										
							loading_box.set('html', message);  
							break;
							case 'booked':
							action_name = 'booked by another user.';
							loading_box.addClass('csmbol-msg-error');								
							var message = session_info+' is '+action_name+'.'										
							loading_box.set('html', message);  
							break;
							default:
							window.alert('return status error: '+response.session_result[entry_id]);
							break;
						};
					}
					if(process == 'makeBooking'){
						//restore system state after booking is done
					}
				}
			});
			
			if(process == 'readyEntriesForBooking'){
				var pending_sec = response.pending_sec;//pending seconds
				btn_ppbtn_div.setStyle('display','inherit');

				enableBtn(btn_bn_restart_booking);	
				if(booking_status == 'admin_in_progress')			
					enableBtn($('btn_admin_book_now'));				
			};			

			if(process == 'makeBooking'){
				enableBtn(btn_bc_new_booking);
			}
		}
	}).send('current_room='+current_room+'&noe='+(booking_entries_info.length-noae)+'&booking_entries='+json_data+'&user='+user+client_info);	
};

function countdown(s, div_id, fire_event){
	var cd = new CountDown({
		element: $(div_id),					
		start: s,
		duration: 1000,
		startFont: '14px',//this line will not work in IE, need to hard-code in CountDown class
		endFont: '14px',
		finish: 0,
		onComplete: function() {
			if(fire_event){
				if(global_countdown_timers == 1){					
//					makeNewBooking();
					disableBtn($('btn_admin_book_now'));
					btn_ppbtn_div.setStyle('display','none');					
				};
			};
			global_countdown_timers -= 1;				
		}
	}).start(); 
	global_countdown_timers += 1;
};
//instruct the controller to save the booking entries info into the session store
//so the info can be retrived after coming back from PayPal
function readyEntriesForBooking(user){
	var tnc_box = new Element('div.csmbol-info-box', {'id': 'tnc-box'});
	var tnc_div = new Element('div',{'text':'To make booking, click to agree with the '});
	var tnc_checkbox = new Element('input',{'type':'checkbox',events: {click: function(){if(this.checked) {this.disabled = true;processEntriesBatch('readyEntriesForBooking', 'standing by for booking', user );}else btn_ppbtn_div.setStyle('display','none');}}});
	var tnc_link = new Element('a', {'text': 'Terms & Contiditions', target:'_blank', styles:{cursor:'pointer'}, events: {click: function(){window.open('http://csm.sg/portal5/components/com_csmbol/views/csmbol/tmpl/csmf.ar.tnc.php', '_blank','scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');}}});	
	tnc_div.grab(tnc_checkbox,'top');
	tnc_div.grab(tnc_link);
	tnc_box.grab(tnc_div);	
	$('csmbol-booking-box').grab(tnc_box, 'top');		
};

//after coming back from PayPal, will get booking entries info from the session store
//and use it to make bookings
function completeClientBookingNow(){

	var booking_entries_info = new Array();
	//getting booking entry info from session store
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=getBookingEntries&format=raw',
		onRequest: function(){
			gotoCompletedPage();
			var loading_box = new Element('div.csmbol-info-box',{'id':'loading-be'});
			var loading_text_div = new Element('div.loading-text', {'text': 'Loading booking entries...'});	
			loading_box.grab(loading_text_div);				
			loading_box.addClass('ajax-loading');	
			$('csmbol-booking-completed-box').grab(loading_box);
		},
		onComplete: function(response){
			var container_box_id = 'csmbol-booking-completed-box';
			if(response.rts =='error'){
				$(container_box_id).set('html', response.rtmsg+response.rtmsg_embeded_code)
				 return;
			}			
			
			$('csmbol-booking-completed-box').empty();
			//constructing the booking_entry_info array
			var noe = response.entries_info_json.length-noae;//-norts;

			for ( i=0; i<noe; i++){
				booking_entries_info = response.entries_info_json;
				var entry_info = {};
				entry_info.seq = response.entries_info_json[i]['seq'];
				entry_info.date = response.entries_info_json[i]['date'];
				entry_info.event_room = response.entries_info_json[i]['event_room'];				
				entry_info.starttime = response.entries_info_json[i]['starttime'];	
				entry_info.endtime = response.entries_info_json[i]['endtime'];
				entry_info.slot_flag = response.entries_info_json[i]['slot_flag'];
				entry_info.booking_status = 'client_confirmed';
				booking_entries_info[i] = entry_info;
			}
//			booking_entries_info[noe] = response[noe];//amt
//			booking_entries_info[noe+1] = response[noe+1];//booking number		
//			booking_entries_info[noe+2] = response[noe+2];//additonal message					
			var user = 'client';
			makeBooking(user, booking_entries_info);
		}
	}).send();	
};

function makeAdminBookingNow(){	
	gotoCompletedPage();
	var user = 'admin';
	//no need booking_entries_info argument 
	//as it can be gen from the booking summary page
	makeBooking(user);	
};

function makeBooking(user, booking_entries_info){
	processEntriesBatch('makeBooking', 'confirmed for you', user, booking_entries_info);
};

function loadPayPal(){
	disableBtn(btn_bn_restart_booking);
	btn_ppbtn_div.setStyle('display','none');
	var loading_box = new Element('div.csmbol-booking-entry', {'id': 'csmbol-booking-entry-loading'});
	loading_box.addClass('ajax-loading');	
	var loading_text = new Element('div.loading-text', {'text': 'Proceeding to payment...'});	
	loading_box.grab(loading_text);
	$('csmbol-booking-box').grab(loading_box, 'top');
};

function atLogin(){
	var at_name = $('at_name').get('value');
	var at_password =$('at_password').get('value');
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=chkATLogin&format=raw',
		onRequest: function(){
			var loading_box = $('at_login_loading_box');
			if(loading_box){
				loading_box.empty().addClass('ajax-loading');
			}else{				
				loading_box = new Element('div.csmbol-info-box.ajax-loading',{'id':'at_login_loading_box'});
				$('at_login_box').grab(loading_box);
			}
			disableBtn($('at_login'));			
		},
		onComplete: function(response){
			$('at_login_loading_box').destroy();			
			if(response.result == 'at_login_success'){
				loadATContent();
			}else{
				window.alert('Login Failed.');
				enableBtn($('at_login'));					
			};
		}
	}).send('at_name='+at_name+'&at_password='+at_password);
}
function loadATContent(){
	$('csmbol-booking-at-box').empty();

	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=getCalImpBoxCode&format=raw',
		onRequest: function(){
			var loading_box = $('at_content_loading_box');
			if(loading_box){
				loading_box.empty().addClass('ajax-loading');
			}else{				
				loading_box = new Element('div.csmbol-info-box.ajax-loading',{'id':'at_content_loading_box'});
				$('csmbol-booking-at-box').grab(loading_box);
			}
		},
		onComplete: function(response){
			$('at_content_loading_box').empty().removeClass('ajax-loading');	
			$('at_content_loading_box').id = 'cal_imp_box';		
//			var at_cal_imp_box = new Element('div.csmbol-info-box',{'id':'cal_imp_box'});
			var at_cal_imp_box = $('cal_imp_box');
			at_cal_imp_box.set('html',response.htmlcode);

			if(!isAdmin(response.user_group)) $('at_impcal_box').setStyle('display','none');
	
			$('csmbol-booking-at-box').grab(at_cal_imp_box);
		}
	}).send();
};
function getCalInfo(){
	var src_cal =$('at_imp_src_cal');
	var des_cal =$('at_imp_des_cal');
	var src_cal_pass =$('at_imp_src_cal_pass');
	var des_cal_pass =$('at_imp_des_cal_pass');
	var src_cal_value = src_cal.get('value');	
	var des_cal_value = des_cal.get('value');
	var src_cal_pass_value = src_cal_pass.get('value');	
	var des_cal_pass_value = des_cal_pass.get('value');	
	if(des_cal_value == 'action.room@csm.sg'){
		window.alert('Des Cal in Protected List');
		return;
	}			
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=getCalInfo&format=raw',
		onRequest: function(){
			var loading_box = new Element('div.csmbol-info-box.ajax-loading',{'id':'get_cal_info_loading_box'});
			$('cal_imp_box').grab(loading_box);
		},
		onComplete: function(response){
			$('get_cal_info_loading_box').destroy();
			var src_cal_sel = $('at_imp_src_cal_list');
			var des_cal_sel = $('at_imp_des_cal_list');			
			src_cal_sel.set('html',response.htmlcode_src);
			des_cal_sel.set('html',response.htmlcode_des);
			$('import_cal_div').setStyle('display','inherit');
		}
	}).send('src_cal='+src_cal_value+'&src_cal_pass='+src_cal_pass_value+'&des_cal='+des_cal_value+'&des_cal_pass='+des_cal_pass_value);	
};
function getCalSlots(){
	var calslot_year =$('at_calslot_year');
	var calslot_month =$('at_calslot_month');
	
	var year = calslot_year.get('value');
	var month = calslot_month.get('value');

	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=getCalSlots&format=raw',
		onRequest: function(){
			if($('calslot_monthly')) $('calslot_monthly').destroy();
			var loading_box = new Element('div.csmbol-info-box.ajax-loading',{'id':'get_cal_info_loading_box'});
			$('at_calslot_box').grab(loading_box);
		},
		onComplete: function(response){
			$('get_cal_info_loading_box').destroy();
			var calslot_monthly = new Element('div.csmbol-info-box',{'id':'calslot_monthly'});
			calslot_monthly.set('html', response.text);
			$('at_calslot_box').grab(calslot_monthly);
		}
	}).send('year='+year+'&month='+month);	
};
function impCal(){
	var src_cal_sel = $('at_imp_src_cal_list');
	var des_cal_sel = $('at_imp_des_cal_list');
	var sel_src = src_cal_sel.get('value');	
	var sel_des = des_cal_sel.get('value');			
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=getCalSpan&format=raw',
		onRequest: function(){
			if($('clear_cal_loading_box')) $('clear_cal_loading_box').destroy();
			var loading_box = $('imp_cal_loading_box');
			if(loading_box){
				loading_box.empty().addClass('ajax-loading');
			}else{				
				loading_box = new Element('div.csmbol-info-box.ajax-loading',{'id':'imp_cal_loading_box'});
				$('import_cal_div').grab(loading_box);
			}
		},
		onComplete: function(response){
			var span_week = response.span_week;
			$('imp_cal_loading_box').removeClass('ajax-loading');
			disableBtn($('at_imp_imp'));
			
			var boxID = new Element('div',{'id':'imp_box'});
  			var percentageID = new Element('div',{'id':'imp_perc'});			
  			var displayID = new Element('div',{'id':'imp_disp','html':'{x}%'});	
			boxID.grab(percentageID);
			  			
			var pb = new dwProgressBar({
				container: $('imp_cal_loading_box'),
				startPercentage: 0,
				speed:1000,
				boxID: 'imp_box',
				percentageID: 'imp_perc'/**/,
				displayID: 'imp_disp',
				displayText: true				
			});
			impCalProgress(pb,span_week,0,response.date_start);			
		}
	}).send('sel_src='+sel_src+'&sel_des='+sel_des);	
};
function impCalProgress(pb,span_week,pos,date_start){
	
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=impCalProgress&format=raw',
		onRequest: function(){
		},
		onComplete: function(response){
			if(pos<span_week){
				if((pos+4)<=span_week){
					pos+=4;
				}else{
					pos += (span_week-pos);
				}
				perc = Math.round(pos*100/span_week);
				pb.set(perc);
				impCalProgress(pb,span_week,pos,response.date_start);
			}else{
				enableBtn($('at_imp_imp'));				
			}
		}
	}).send('date_start='+date_start);	
}
function clearCal(){
	var des_cal_sel = $('at_imp_des_cal_list');
	var sel_des = des_cal_sel.get('value');			
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=getCalSpan&format=raw',
		onRequest: function(){
			if($('imp_cal_loading_box')) $('imp_cal_loading_box').destroy();			
			var loading_box = $('clear_cal_loading_box');
			if(loading_box){
				loading_box.empty().addClass('ajax-loading');
			}else{				
				loading_box = new Element('div.csmbol-info-box.ajax-loading',{'id':'clear_cal_loading_box'});
				$('import_cal_div').grab(loading_box);
			}
		},
		onComplete: function(response){
			var span_week = response.span_week;
			$('clear_cal_loading_box').removeClass('ajax-loading');
			disableBtn($('at_imp_clear'));
			
			var boxID = new Element('div',{'id':'imp_box'});
  			var percentageID = new Element('div',{'id':'imp_perc'});			
  			var displayID = new Element('div',{'id':'imp_disp','html':'{x}%'});	
			boxID.grab(percentageID);
			  			
			var pb = new dwProgressBar({
				container: $('clear_cal_loading_box'),
				startPercentage: 0,
				speed:1000,
				boxID: 'imp_box',
				percentageID: 'imp_perc'/**/,
				displayID: 'imp_disp',
				displayText: true				
			});
			clearCalProgress(pb,span_week,0);			
		}
	}).send('sel_des='+sel_des);	
};
function clearCalProgress(pb,span_week,pos){
	
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=clearCalProgress&format=raw',
		onRequest: function(){
		},
		onComplete: function(response){
			if(pos<span_week){
				if((pos+4)<=span_week){
					pos+=4;
				}else{
					pos += (span_week-pos);
				}
				perc = Math.round(pos*100/span_week);
				pb.set(perc);
				clearCalProgress(pb,span_week,pos);
			}else{
				enableBtn($('at_imp_clear'));				
			}
		}
	}).send('pos='+pos);	
}
function selRoom(){
	current_room = $('at_selroom_room').get('value');
	new Request.JSON({
		url:  'index.php?option=com_csmbol&controller=csmbol&view=csmbol&task=selRoom&format=raw',
		onRequest: function(){
			var loading_box = new Element('div.csmbol-info-box',{'id':'at_selroom_loading'});
			loading_box.addClass('ajax-loading');
			$('at_selroom_div').grab(loading_box);
		},
		onComplete: function(response){
			$('at_selroom_loading').destroy();
			var rates = {}; rates = response.rates;
			assignRates(response.rates);
			makeNewBooking();			
		}
	}).send('current_room='+current_room);		
};

function checkEmail(email_input) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email_input)){
		return (true)
	}
	alert("Invalid E-mail Address! Please re-enter.")
	return (false)
}

function checkPhone(phone_input) {
	if(/^(\+{0,1}\d{2})*\s*(\(\d{2}\)\s*)*\d{4}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/.test(phone_input)){
		return (true)
	}
	alert("Invalid Phone Number! Please re-enter.")
	return (false)
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}